试图获取所有月份的数据,但LEFT JOIN无法正常工作

时间:2019-05-16 21:34:42

标签: sql left-join

我希望显示所有月份的数据,即使该月没有数据也是如此。下面的代码不起作用...

;with months (mon) as
    (select mon from (values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12)) a (mon))
SELECT c.CASE_NBR, c.SEVERITY_OF_COLLISION_ID, c.OCCURENCE_TIMESTAMP, DATEPART(MONTH, c.OCCURENCE_TIMESTAMP) AS month1, 
    CASE WHEN c.SEVERITY_OF_COLLISION_ID = '4' THEN 'Fatal Collisions' WHEN c.SEVERITY_OF_COLLISION_ID = '5' THEN 'Non-Fatal Collisions' END AS coll_severity_type, 
    CASE WHEN months.mon = '1' THEN 'January' 
         WHEN months.mon = '2' THEN 'February' 
         WHEN months.mon = '3' THEN 'March'
         WHEN months.mon = '4' THEN 'April' 
         WHEN months.mon = '5' THEN 'May' 
         WHEN months.mon = '6' THEN 'June' 
         WHEN months.mon = '7' THEN 'July' 
         WHEN months.mon = '8' THEN 'August'
         WHEN months.mon = '9' THEN 'September' 
         WHEN months.mon = '10' THEN 'October' 
         WHEN months.mon = '11' THEN 'November' 
         WHEN months.mon = '12' THEN 'December' 
     END AS month_name
FROM ECRDBA.COLLISIONS AS c
    left join months on months.mon = DATEPART(MONTH, c.OCCURENCE_TIMESTAMP)
    INNER JOIN ECRDBA.CL_OBJECTS AS o ON o.COLLISION_ID = c.ID 
    INNER JOIN ECRDBA.OBJECT_TYPES AS ot ON ot.ID = o.OBJECT_TYPE_ID 
where (c.SEVERITY_OF_COLLISION_ID NOT IN ('6')) AND (c.CASE_YEAR IN (2016)) and (ot.CODE = '06')

2 个答案:

答案 0 :(得分:0)

您的查询子句应类似于:

SELECT . . .
FROM months LEFT JOIN
     ECRDBA.COLLISIONS c 
     ON months.mon = DATEPART(MONTH, c.OCCURENCE_TIMESTAMP) AND
        c.SEVERITY_OF_COLLISION_ID NOT IN ('6') AND
        c.CASE_YEAR IN (2016) LEFT JOIN
     ECRDBA.CL_OBJECTS o
     ON o.COLLISION_ID = c.ID LEFT JOIN
     ECRDBA.OBJECT_TYPES ot
     ON ot.ID = o.OBJECT_TYPE_ID AND ot.CODE = '06'

您需要从要保留所有行的表开始。然后,随后的join应该是left join,并且这些表上的条件应该在on子句中,而不是where中。

答案 1 :(得分:0)

只需从如下所示的“月”表开始,您就应该获得预期的结果。

 FROM months
 LEFT JOIN  ECRDBA.COLLISIONS AS c
     ON months.mon = DATEPART(MONTH, c.OCCURENCE_TIMESTAMP)
 ......