Sql 按列值分组,将两个字段相加得到差值
我有一个表格,格式如下图所示,作为数据库表格。Sql 按列值分组,将两个字段相加得到差值,sql,aggregation,cross-apply,Sql,Aggregation,Cross Apply,我有一个表格,格式如下图所示,作为数据库表格。 我想从这个表中生成一个报告。给出了期望的格式。请帮助我完成查询。假设在T-SQL中的表中只能有两种类型,您可以将查询编写为: 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 sel
我想从这个表中生成一个报告。给出了期望的格式。请帮助我完成查询。假设在
T-SQL
中的表中只能有两种类型,您可以将查询编写为:
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
我猜你应该展示你已经尝试过的内容,否则会有反对票,但是你想要的内容的描述很好。哪个数据库是MYSQL/SQL Server/Oracle?只能有2种类型和给定格式的数据吗?提示:在Oracle中,你可以通过4个子选择进行双选择,每种类型一次,然后进行联合。。。很简单,但可能不是最好的方法。@maraca:我的查询有点长,需要替换文件名,因为它们很敏感。但很快就会更改列名并发布查询。受您的查询启发。是类型是固定的否。我正在以ur格式更改我的查询。将很快更新。