如何对2个查询的计数求和?

时间:2018-10-17 23:28:50

标签: sql sql-server tsql

--Query 1 - Processed
select cast(a.startdate as date), count(distinct a.signatureid)
from asset a
join assetlog al on al.assetid = a.assetid
where a.stream = 50
and al.priority in ('1','3')
group by cast(a.startdate as date)
order by cast(a.startdate as date)

--Query 2 - Unprocessed
select cast(a.startdate as date), count(distinct a.signatureid)
from asset a
join assetlog al on al.assetid = a.assetid
where a.stream = 49
and a.order is not null
and al.priority = 2
group by cast(a.startdate as date)
order by cast(a.startdate as date)

嗨,每天查询部分以上的查询最终最终会占用一列的计数。一个发现“已处理”记录,另一个发现“未处理”。不幸的是,表中没有简单的列可以确定这一点。

现在需要一个查询,该查询每天汇总两个表的计数。实现此目标的最佳方法是什么?顺便说一句,在SSMS中。

谢谢!

2 个答案:

答案 0 :(得分:0)

如果某项资产可以在给定的日期同时出现在查询1和查询2中,则该解决方案在该天仅会对其计数一次:

--Query 1 - Processed
select cast(a.startdate as date), count(distinct a.signatureid)
from asset a
join assetlog al on al.assetid = a.assetid
where (a.stream = 50
and al.priority in ('1','3'))
or (a.stream = 49
and a.order is not null
and al.priority = 2)
group by cast(a.startdate as date)
order by cast(a.startdate as date)

此查询源自问题中的两个查询,但使用OR组合了WHERE子句。

答案 1 :(得分:0)

如果您无法按照注释中的建议合并查询,则可以使用full join,如下所示:

with a ([date], [sum]) as (
    select      CAST('20180101' as date)                as  [date]
        ,       2                                       as  [sum]
    union all
    select      CAST('20180102' as date)                as  [date]
        ,       4                                       as  [sum]
)

, b ([date], [sum]) as (
    select      CAST('20180102' as date)                as  [date]
        ,       3                                       as  [sum]
    union all
    select      CAST('20180103' as date)                as  [date]
        ,       8                                       as  [sum]
)

select      ISNULL(a.[date], b.[date])                  as  [date]
    ,       ISNULL(a.[sum], 0) + ISNULL(b.[sum], 0)     as  [sum]
from        a
full join   b
    on      a.[date]                                    =   b.[date]
order by    ISNULL(a.[date], b.[date])