如何包含不匹配的行?

时间:2015-06-26 16:50:35

标签: sql sql-server-2012

此脚本按预期工作。

  select a.Loc, Count(a.PID) as TotalVisit
    from AccountCount as a
    inner join Data as b
    on a.PID = b.PID
    where 
    cast(a.DateTime as date) between cast(b.ADateTime as date) and cast(b.DDateTime as date) 
and year(a.DateTime)=2015
and month(a.DateTime)=05  
    group by a.Loc
    order by a.Loc;

但是,我需要在Data表中包含更多的PID。这些PID不在AccountCount表中。

    select LocID, PID 
    from Data 
    where 
    and cast(ADateTime as date) = cast(DDateTime as date)
and year(ADateTime) = 2015
and month(ADateTime)=05
    order by LocID;

简单来说,我需要在第一个脚本和第二个脚本之间建立联合。我试图加入数据表,但它没有用。

使用xQbert提供的UNION ALL,我得到的结果如。

Loc         TotalVisit
1st floor   20
2nd floor   5
3rd floor   8
1st floor   2

需要

Loc         TotalVisit
1st floor   22
2nd floor   5
3rd floor   8

请帮忙。 谢谢。

1 个答案:

答案 0 :(得分:0)

我认为只要正确设置ON条件并将Where子句移动到连接,右连接就会起作用(因为如果留在where子句中,它会使右连接成为内连接。)连接结果为空记录,由where子句排除,从而否定外连接))

union all不允许聚合数据。对我来说,外连接是正确的做法。我们只需要更好地理解数据,使其正常工作。但是,使用union只需简单总结结果......使用外部查询...但是现在您已经提供了一些示例数据,我可能能够找出为什么外连接不起作用)

使用union all ...(我的目的是让它工作然后改进它)

Select X.Loc, sum(X.TotalVisit) as TotalVisit
from (SELECT a.Loc as LOC, Count(a.PID) as TotalVisit
    from AccountCount as a
    inner join Data as b
    on a.PID = b.PID
    where 
    cast(a.DateTime as date) between cast(b.ADateTime as date) and cast(b.DDateTime as date)   
    group by a.Loc
    UNION ALL
    select LocID as LOC, count(PID)
    from Data 
    where 
    and cast(ADateTime as date) = cast(DDateTime as date)
    GROUP BY by LocID
) X
 GROUP BY X.Loc
 ORDER BY X.LOC

这导致我...我认为这将工作从AccountCount.Loc和Data.LocID获取位置的第一个非null值并使用它。注意没有where子句......

SELECT Coalesce(A.Loc, B.LocID) as Loc,  count(B.PID) as TotalVisit
FROM Data B
LEFT JOIN AccountCount A
 on B.PID = A.PID
 and (cast(a.DateTime as date) between cast(b.ADateTime as date) and cast(b.DDateTime as date) 
  OR  cast(B.ADateTime as date) = cast(B.DDateTime as date))
GROUP BY Coalesce(A.Loc, B.LocID)
Order by Coalesce(A.Loc, B.LocID)