2016-11-09 63 views
0

我試圖過濾出由特定用戶添加的結果,同時保持每一天,因爲此查詢將用於報表中的圖表。當我刪除t2.createdBy <> 21時,我得到了所有的日期,但我也需要結果按此過濾纔是正確的。T-SQL:如何保留左連接但過濾器查詢

查詢:

SELECT 
    t1.DateFull, COUNT(t2.ContainerWashedDate) as Washes 
FROM 
    DateLookup t1 
LEFT JOIN 
    factContainerWash t2 ON t1.Datefull = t2.ContainerWashedDate 
WHERE 
    (t1.DateFull >= '10/5/2016') 
    AND (t1.DateFull <= '11/9/2016') 
    AND t2.createdBy <> 21 
GROUP BY 
    t1.DateFull 
ORDER BY 
    DateFull 

結果:

DateFull     | Washes 
-------------------------+------- 
2016-10-05 00:00:00.000 | 1231 
2016-10-06 00:00:00.000 | 466 
2016-10-10 00:00:00.000 | 84 
2016-10-12 00:00:00.000 | 75 

預期結果:

DateFull     | Washes 
-------------------------+------- 
2016-10-05 00:00:00.000 | 1231 
2016-10-06 00:00:00.000 | 466 
2016-10-07 00:00:00.000 | 655 
2016-10-08 00:00:00.000 | 23 
+0

但'createdBy' **不能**是21,如果它根本不存在。您首先需要解決一個邏輯問題。 – Amit

回答

2

以下三種方法。當我開始回答這個問題時,我意識到可能會發生細微差別的事情。可能所有這三種都有效,但第一種可能並不總是奏效。

我懷疑你只是想要一個額外的NULL比較:

SELECT t1.DateFull, COUNT(t2.ContainerWashedDate) as Washes 
FROM DateLookup t1 LEFT JOIN 
    factContainerWash t2 
    ON t1.Datefull = t2.ContainerWashedDate 
WHERE t1.DateFull >= '2016-10-05' and 
     t1.DateFull <= '2016-11-09' and 
     (t2.createdBy <> 21 or t2.createdBy is null) 
GROUP BY t1.DateFull 
ORDER BY DateFull; 

,或者,使用條件彙總:

SELECT t1.DateFull, 
     COUNT(CASE WHEN createdBy <> 21 THEN t2.ContainerWashedDate END) as Washes 
FROM DateLookup t1 LEFT JOIN 
    factContainerWash t2 
    ON t1.Datefull = t2.ContainerWashedDate 
WHERE t1.DateFull >= '2016-10-05' and 
     t1.DateFull <= '2016-11-09' 
GROUP BY t1.DateFull 
ORDER BY DateFull; 

它也有可能是移動狀態的ON條款做了你需要的工作:

SELECT t1.DateFull, 
     COUNT(t2.ContainerWashedDate) as Washes 
FROM DateLookup t1 LEFT JOIN 
    factContainerWash t2 
    ON t1.Datefull = t2.ContainerWashedDate AND t2.createdBy <> 21 
WHERE t1.DateFull >= '2016-10-05' and 
     t1.DateFull <= '2016-11-09' 
GROUP BY t1.DateFull 
ORDER BY DateFull; 
+1

我發現你的第二種方法對我最合適。 –

2

當你在WHERE子句中使用了t2.CreatedBy,您使得LEFT JOIN成爲INNER JOIN。怎麼樣這樣的事情:

SELECT 
    t1.DateFull 
    , COALESCE(t2.Washes, 0) AS Washes 
FROM 
    (
    SELECT 
     ContainerWahsedDate 
     , COUNT(ContainerWahsedDate) AS Washes 
    FROM 
     factConainerWash 
    WHERE 
     ContainerWahsedDate BETWEEN '2016-10-05' AND '2016-11-09' 
     AND CreatedBy <> 21 
    GROUP BY 
     ContainerWashedDate 
    ) t2 
    LEFT JOIN DateLookup t1 ON t1.DateFull = t2.ContainerWahsedDate 
WHERE 
    t2.DateFull BETWEEN '2016-10-05' AND '2016-11-09'