按列值分组并通过总结两个字段来获得差异

时间:2015-07-31 08:53:38

标签: sql aggregation cross-apply

我的表格格式如下图所示。 enter image description here 从该表我想生成一个报告。给出了预期的格式。帮我解决一下问题。

1 个答案:

答案 0 :(得分:2)

假设T-SQL中的表格中只能有2个类型,您可以将查询编写为:

select PaymentType,
[Exists only in old],
diff,
[Exists only in New],
([Exists only in old]+diff+[Exists only in New]) as Total
from
(
-- Fetch Data for Type 1
select 'Type1' as PaymentType,
       sum( case when EXIST_IN_New = 'Not Exists' and EXIST_IN_Old='Exists' 
            then Old_Type_1
            else 0 end) as 'Exists only in old',
       sum( case when EXIST_IN_New = 'Exists' and EXIST_IN_Old='Not Exists' 
            then New_Type_1
            else 0 end) as 'Exists only in New',
       sum( case when EXIST_IN_New = 'Exists' and EXIST_IN_Old='Exists' 
            then Old_Type_1
            else 0 end) - 
         sum( case when EXIST_IN_New = 'Exists' and EXIST_IN_Old='Exists' 
            then New_Type_1
            else 0 end)   as diff                  
from 
Test
union
-- Fetch Data for Type 2
select 'Type2' as PaymentType,
       sum( case when EXIST_IN_New = 'Not Exists' and EXIST_IN_Old='Exists' 
            then Old_Type_2
            else 0 end) ,
       sum( case when EXIST_IN_New = 'Exists' and EXIST_IN_Old='Not Exists' 
            then New_Type_2
            else 0 end) ,
       sum( case when EXIST_IN_New = 'Exists' and EXIST_IN_Old='Exists' 
            then Old_Type_2
            else 0 end) - 
         sum( case when EXIST_IN_New = 'Exists' and EXIST_IN_Old='Exists' 
            then New_Type_2
            else 0 end)                   
from 
Test
)as T

DEMO