1
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

我需要获取合同开始日期和合同结束日期之间的差异

4

2 回答 2

1

确保您正在比较日期表示而不是代码(“2011-12-12”,而不是“TIME_101”;您是否在两个表之间执行正确的连接?)并且这些表示使用正确的格式(其中没有出现在您的问题的任何地方)。

于 2013-10-08T09:15:54.810 回答
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)

希望这可以帮助!!!

于 2013-10-08T11:37:55.867 回答