Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 按列值分组,将两个字段相加得到差值_Sql_Aggregation_Cross Apply - Fatal编程技术网

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格式更改我的查询。将很快更新。