2016-11-09 55 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'