答案 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