将计数与Group by从不同的表组合到一个结果集

时间:2018-01-18 09:22:15

标签: sql sql-server

我必须从3个不同的表中找到最近几天的每日,这是查询

    select CONVERT(Date,CompletedDate) as CompletedDate, count(ID) as Count
    from Table1 where CompletedDate >= DATEADD(day,-5, GetDate())
    group by CONVERT(Date,CompletedDate)

    select CONVERT(Date,CompletedDate) as CompletedDate, count(ID) as Count
    from Table2 where CompletedDate >= DATEADD(day,-5, GetDate())
    group by CONVERT(Date,CompletedDate)

    select CONVERT(Date,CompletedDate) as CompletedDate, count(ID) as Count
    from Table3 where CompletedDate >= DATEADD(day,-5, GetDate())
    group by CONVERT(Date,CompletedDate)

是否可以将一天中每天的计数总计为单个SQL中的单个数据集

1 个答案:

答案 0 :(得分:2)

请尝试这样的事情..如果您还有其他需要,请提供样品输入和输出。

select CompletedDate,SUM([Count]) cnt FROM 
(
    select CONVERT(Date,CompletedDate) as CompletedDate, count(ID) as Count
    from Table1 where CompletedDate >= DATEADD(day,-5, GetDate())
    group by CONVERT(Date,CompletedDate)
    UNION ALL
    select CONVERT(Date,CompletedDate) as CompletedDate, count(ID) as Count
    from Table2 where CompletedDate >= DATEADD(day,-5, GetDate())
    group by CONVERT(Date,CompletedDate)
    UNION ALL
    select CONVERT(Date,CompletedDate) as CompletedDate, count(ID) as Count
    from Table3 where CompletedDate >= DATEADD(day,-5, GetDate())
    group by CONVERT(Date,CompletedDate)
)x GROUP BY CompletedDate