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()
函数。根据实际需求,可以调整日期字段、时间单位和比较条件来满足不同场景的查询需求。