Oracle Left Join不返回所有行

时间:2015-09-25 15:39:45

标签: sql oracle

我正在使用以下CTE。第一部分收集所有独特的人,第二部分在特定时间范围内将独特的人与事件联系起来。我期待所有行都从我独特的人员表中返回,即使他们没有在时间范围内发生事件。但事实并非如此。

WITH DISTINCT_ATTENDING(ATTENDING) AS 
(
SELECT DISTINCT ATTENDING
FROM PEOPLE
WHERE ATTENDING IS NOT NULL
), -- returns 62 records
EVENT_HISTORY(ATTENDING, TOTAL) AS
(
SELECT  C.ATTENDING,
        COUNT(C.ID) 
FROM DISTINCT_ATTENDING D
LEFT JOIN PEOPLE C
ON C.ATTENDING = D.ATTENDING 
AND TO_DATE(C.DATE, 'YYYYMMDD') < TO_DATE('20140101', 'YYYYMMDD') 

GROUP BY C.ATTENDING 
ORDER BY C.ATTENDING  

)

SELECT * FROM EVENT_HISTORY; -- returns 49 rows

我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

强尼

问题出在“C.ATTENDING”栏目中,只需更改为“D.ATTENDING”

SELECT  D.ATTENDING,
        COUNT(C.ID) 
FROM DISTINCT_ATTENDING D
LEFT JOIN PEOPLE C
ON C.ATTENDING = D.ATTENDING 
AND TO_DATE(C.DATE, 'YYYYMMDD') < TO_DATE('20140101', 'YYYYMMDD') 

GROUP BY D.ATTENDING 
ORDER BY D.ATTENDING 

答案 1 :(得分:1)

您的查询似乎太复杂了。我认为以下内容也是如此:

SELECT P.ATTENDING,
       SUM(CASE WHEN TO_DATE(P.DATE, 'YYYYMMDD') < TO_DATE('20140101', 'YYYYMMDD')
                THEN 1 ELSE 0 END)
FROM PEOPLE P
WHERE P.ATTENDING IS NOT NLL
GROUP BY P.ATTENDING 
ORDER BY P.ATTENDING ; 

您的问题是您是按left join第二个表中的列聚合的。当没有匹配时,这是NULL