在 SQL 中,DateDiff 函数用于计算两个日期之间的差异。DateDiff 函数有三个参数:datepart、startdate 和 enddate。datepart 参数表示要计算的日期部分,如年、月、日等;startdate 和 enddate 参数表示要计算差异的两个日期。
以下是一些高级用法:
SELECT DATEDIFF(year, '2020-01-01', '2022-01-01') AS Difference;
SELECT DATEDIFF(month, '2020-01-01', '2022-01-01') AS Difference;
SELECT DATEDIFF(day, '2020-01-01', '2022-01-01') AS Difference;
SELECT DATEDIFF(hour, '2020-01-01 00:00:00', '2020-01-01 05:00:00') AS Difference;
SELECT DATEDIFF(minute, '2020-01-01 00:00:00', '2020-01-01 00:30:00') AS Difference;
SELECT DATEDIFF(second, '2020-01-01 00:00:00', '2020-01-01 00:00:30') AS Difference;
SELECT DATEDIFF(millisecond, '2020-01-01 00:00:00.000', '2020-01-01 00:00:00.100') AS Difference;
SELECT DATEDIFF(microsecond, '2020-01-01 00:00:00.000000', '2020-01-01 00:00:00.001000') AS Difference;
SELECT DATEDIFF(nanosecond, '2020-01-01 00:00:00.000000000', '2020-01-01 00:00:00.000001000') AS Difference;
DECLARE @startdate DATETIME = '2020-01-01';
DECLARE @enddate DATETIME = '2022-01-01';
SELECT DATEDIFF(year, @startdate, @enddate) AS Difference;
请注意,这些示例仅适用于 SQL Server。其他数据库系统可能具有不同的语法和功能。
领取专属 10元无门槛券
手把手带您无忧上云