我有几个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
答案 0 :(得分: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