Sql Server 2008 Datediff在select语句中有条件。
我有以下查询,需要帮助了解为什么我会得到这些结果和我的问题的最佳解决方案。
SELECT DISTINCT l.program, l.id
,(DATEDIFF(DAY, B.FIRST_DT , B.FIRST_second_DT))days_between1
,(DATEDIFF(DAY, C.FIRST_DT , C.FIRST_second_DT))days_between2
FROM l
LEFT JOIN l B ON L.id = B.id AND L.SERVICE_DATE = B.SERVICE_DATE
AND B.FIRST_DT IS NOT NULL AND B.FIRST_DT IS NOT NULL
AND l.IS ='0' AND L.FIRST_V_DT IS NOT NULL
LEFT JOIN l C ON L.id = C.id AND L.SERVICE_DATE = C.SERVICE_DATE
AND C.FIRST_DT IS NOT NULL
AND C.FIRST_A_DT IS NOT NULL AND L.IS ='1'
AND L.FIRST_DT IS NOT NULL
WHERE 1=1
我得到了两行
Program id daysbetween1 daysbetween2
blue 1 null 3
blue 1 4 null
如何获得一行,如下所示,为什么我会得到两行?
Program id daysbetween1 daysbetween2
blue 1 4 3
答案 0 :(得分:2)
您可以尝试这种方式:
SELECT l.program, l.id
,MAX((DATEDIFF(DAY, B.FIRST_DT , B.FIRST_second_DT))) days_between1
,MAX((DATEDIFF(DAY, C.FIRST_DT , C.FIRST_second_DT))) days_between2
FROM l
LEFT JOIN l B ON L.id = B.id AND L.SERVICE_DATE = B.SERVICE_DATE
AND B.FIRST_DT IS NOT NULL AND B.FIRST_DT IS NOT NULL
AND l.IS ='0' AND L.FIRST_V_DT IS NOT NULL
LEFT JOIN l C ON L.id = C.id AND L.SERVICE_DATE = C.SERVICE_DATE
AND C.FIRST_DT IS NOT NULL
AND C.FIRST_A_DT IS NOT NULL AND L.IS ='1'
AND L.FIRST_DT IS NOT NULL
GROUP BY l.program, l.id
除非您从过滤器的某种动态连接中获取此SQL,否则不需要where
条件。