SELECT datediff(Contract_Start_Date,Contract_End_Date) FROM testdata;
此查询始终返回null
我的约会对象是
Time ID Date
TIME_101 2011-12-12
TIME_102 2011-12-13
TIME_103 2011-12-14
TIME_104 2011-12-15
TIME_105 2011-12-16
TIME_106 2011-12-19
TIME_107 2011-12-20
TIME_108 2011-12-21
TIME_109 2011-12-22
和
Contract ID Contract Start Date Contract End Date
CON_001 TIME_101 TIME_1248
CON_002 TIME_102 TIME_1249
CON_003 TIME_103 TIME_1250
CON_004 TIME_104 TIME_1251
CON_005 TIME_105 TIME_1252
CON_006 TIME_106 TIME_1253
我需要获取合同开始日期和合同结束日期之间的差异
答案 0 :(得分:1)
确保您正在比较日期表示而不是代码('2011-12-12',而不是'TIME_101';您是否在两个表之间执行正确的连接?)并且使用正确的方法将这些表示解析为日期格式(在您的问题中不会出现在任何地方)。
答案 1 :(得分:0)
用于计算日期差异的T-SQL查询:
select Contract_ID, datediff(Day,Contract_Start_Dt,Contract_End_Dt) as [Datediff]
from
(
select TD.Contract_ID,
(
select T1.[Date]
from table1 T1
where T1.Time_ID = TD.Contract_Start_Date
) as Contract_Start_Dt
,
( select T1.[Date]
from table1 T1
where T1.Time_ID = TD.Contract_End_Date
) as Contract_End_Dt
FROM testdata TD
) as T
[编辑:在T-SQL查询后按月分组的开始日期和结束日期之间存在差异,以获得合同计数]
select COUNT(*)
from
(
select Contract_ID,Contract_Start_Dt,Contract_End_Dt, datediff(Day,Contract_Start_Dt,Contract_End_Dt) as [Datediff]
from
(
select TD.Contract_ID,
(
select T1.[Date]
from table1 T1
where T1.Time_ID = TD.Contract_Start_Date
) as Contract_Start_Dt
,
( select T1.[Date]
from table1 T1
where T1.Time_ID = TD.Contract_End_Date
) as Contract_End_Dt
FROM testdata TD
) as T) as T1
where [Datediff]>0 -- case when there exists a difference between two dates
group by MONTH(Contract_Start_Dt)
希望这有帮助!!!