SQL将行数转换为列

时间:2016-09-07 11:28:13

标签: sql-server pivot

我有一个查询,按代理商返回两种类型" Vente"和" Recouv"。我希望我的请求显示一行,其中包含列" Commission"。

的总和

这张照片展示了我拥有的和我想要的东西:

 select codeAgence,CASE WHEN (TypeOperation =0) THEN 'Vente' ELSE 'Recouvrement' END  as 'Type',
 count(*) 'Nb',SUM(PxVenteHT ) 'C.A',SUM(acompte) 'Montant',SUM(MontantCommission ) 'Commission' from Commission_Archive
  group by CodeAgence,TypeOperation
  order by CodeAgence

Enter image description here

1 个答案:

答案 0 :(得分:1)

我认为这可能会做你想要的,但由于你的问题缺乏适当的样本源数据,我还没有对它进行测试。

SELECT 
    codeAgence,
    COUNT(CASE WHEN (TypeOperation = 0) THEN 'Vente' ELSE NULL END) 'Nb Vente',
    SUM(CASE WHEN (TypeOperation = 0) THEN PxVenteHT ELSE 0 END) 'C.A',
    COUNT(CASE WHEN (TypeOperation <> 0) THEN 'Recouve' ELSE NULL END) 'Nb Recouve',
    SUM(CASE WHEN (TypeOperation <> 0) THEN acompte ELSE 0 END) 'Montant Recouve',
    SUM(MontantCommission) 'Commission' 
FROM Commission_Archive 
GROUP BY CodeAgence
ORDER BY CodeAgence 

关键是将条件聚合技术应用于应在Nb / Recouve上拆分的所有聚合列,并更改分组。