【问题标题】:How can I combine two similar grouped result sets into one?如何将两个相似的分组结果集合并为一个?
【发布时间】:2012-11-27 19:28:47
【问题描述】:

我有几个 SQL Server 2012 查询正在工作,但不知道如何将它们组合成一个结果集。我希望将 [Total Claims] 和 [Reversed Claims] 视为同一结果集中的相邻列。这可能吗?

select [Date], DATENAME(weekday, [Date]) as [Day], [Total Claims]
from (Select [Date], count(*) as [Total claims] from ClaimHistoryView group by [Date] )
as CountByDay
order by [Date] desc

select [Date], DATENAME(weekday, [Date]) as [Day], [Reversed Claims]
from (Select [Date], count(*) as [Reversed Claims] from ClaimHistoryView where status = 2 group by [Date] ) as CountByDay
order by [Date] desc

【问题讨论】:

    标签: sql sql-server-2012


    【解决方案1】:

    诀窍是使用“union all”将这两个查询与另一列结合起来,该列指示数据的来源,然后进行选择性透视。唔。复杂的解释(对不起,德语)

    这应该可以解决问题

    select [Date], 
           DATENAME(weekday, [Date]) as [Day], 
           sum(case when Source = 1 then value else 0 end) as [Total Claims],
           sum(case when Source = 2 then value else 0 end) as [Reversed Claims]
    from
    (
      select 
            1 as source, 
            [Date], 
            count(*) as value 
      from  ClaimHistoryView 
      group by [Date]
    union all
      select 
            2 as source,
            [Date],  
            count(*) as value 
      from  ClaimHistoryView 
      where status = 2 
      group by [Date]
    ) as CountByDay 
    Group by [Date]
    order by [Date] desc
    

    【讨论】:

    • 非常感谢。请注意,“2 作为来源”之后需要一个逗号。
    猜你喜欢
    • 1970-01-01
    • 2018-04-04
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2013-07-25
    相关资源
    最近更新 更多