Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.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 Server:将同一行中的2列分组_Sql_Sql Server_Tsql_Group By_Pivot - Fatal编程技术网

SQL Server:将同一行中的2列分组

SQL Server:将同一行中的2列分组,sql,sql-server,tsql,group-by,pivot,Sql,Sql Server,Tsql,Group By,Pivot,我有这个疑问 select Id, case when isThirdParty = 0 then sum(total) end as FirstPartyFees, case when isThirdParty = 1 then sum(total) end as ThirdPartyFees from MyTable group by id, isThirdParty 我得到了这个结果 Id

我有这个疑问

select 
    Id,
    case when isThirdParty = 0 then sum(total) end as FirstPartyFees,
    case when isThirdParty = 1 then sum(total) end as ThirdPartyFees
from 
    MyTable
group by 
    id, isThirdParty
我得到了这个结果

Id                                    FirstPartyFees                          ThirdPartyFees
------------------------------------ --------------------------------------- ---------------------------------------
DA29BDC0-BE3F-4193-BFDC-493B354CE368 15.00                                   0.00
2EF0B590-FE4F-42E8-8426-5864A739C16B 5.00                                    0.00
246DC3D8-732F-4AE3-99F3-BDEBF98F7719 15.00                                   0.00
FC81F220-ED54-48FE-AE1B-C394492E82A4 5.00                                    0.00
336D9CF1-6970-48BA-90E5-C7889914DDCB 114.00                                  0.00
6F2EEF6F-5FA1-42E5-A988-DB88037DAB92 5.00                                    0.00
80763B37-68E1-4716-B32A-FE82C1700B52 15.00                                   0.00
DA29BDC0-BE3F-4193-BFDC-493B354CE368 0.00                                    1.00
2EF0B590-FE4F-42E8-8426-5864A739C16B 0.00                                    1.00
246DC3D8-732F-4AE3-99F3-BDEBF98F7719 0.00                                    1.00
FC81F220-ED54-48FE-AE1B-C394492E82A4 0.00                                    1.00
336D9CF1-6970-48BA-90E5-C7889914DDCB 0.00                                    0.00
6F2EEF6F-5FA1-42E5-A988-DB88037DAB92 0.00                                    1.00
80763B37-68E1-4716-B32A-FE82C1700B52 0.00                                    1.00

如你所见,我为第一方和第三方提供了副本。如何在一行中对同一Id的第一方和第三方合计进行分组?

您正在寻找条件聚合

您应该将大小写表达式移到sum中,并从GROUPBY子句中删除isThirdParty

因为iThirdParty是一个指标,所以您也可以使用数学:

select Id, SUM(total * (1 - isThirdParty)) as FirstPartyFees,
   SUM(total * isThirdParty) as ThirdPartyFees
frOm MyTable
group by id;

你对这么快的答案投了赞成票。我迟到了30秒:-@TimBiegeleisen:谢谢。。。我从你和其他SQL大师那里学到了速度在这里如此重要的艰难过程。。。
select Id, SUM(total * (1 - isThirdParty)) as FirstPartyFees,
   SUM(total * isThirdParty) as ThirdPartyFees
frOm MyTable
group by id;