SQL 的 DATEDIFF()
函數用于計算兩個日期之間的差值
以下是一些使用 DATEDIFF()
函數的查詢示例和技巧:
SELECT DATEDIFF(day, '2021-01-01', '2021-01-31') AS days_difference;
SELECT * FROM users
WHERE DATEDIFF(day, registration_date, GETDATE()) <= 30;
SELECT
DATEDIFF(year, hire_date, GETDATE()) AS years_of_experience,
COUNT(*) AS num_employees
FROM employees
GROUP BY DATEDIFF(year, hire_date, GETDATE());
SELECT * FROM users
WHERE MONTH(birthdate) = MONTH(DATEADD(month, 1, GETDATE()))
AND DAY(birthdate) = DAY(DATEADD(month, 1, GETDATE()));
SELECT * FROM orders
WHERE DATEDIFF(day, order_date, '2021-01-01') % 7 = 0;
這些示例展示了如何在 SQL 查詢中使用 DATEDIFF()
函數。根據實際需求,可以調整日期字段、時間單位和比較條件來滿足不同場景的查詢需求。