在MS SQL查询输出中的pivot

时间:2016-09-06 07:20:36

标签: sql-server pivot pivot-table

我从这个查询中尝试这个查询,我得到的结果有多个同名记录

    SELECT 
       S.Fruit
       ,S.RegNo
       ,SUM(total) total 
    FROM (SELECT  
              RV.Fruit
              ,RV.RegNo
              ,COUNT(vv.Fruit) as total
              , RV.MS 
          from vv inner join RV on vv.MID= RV.ID 
          inner join Re on RV.RID=Re.RID 
          WHERE Reg.SDate>='2016-04-0100:00:00.000' and 
                Reg.EDate<= '2016-04-30 23:59:59.000'  and 
                Reg.Reg= 'UK' and RV.RegNo ='375' AND 
                Fruit <> '' 
          GROUP BY  RV.Fruit,RV.RegNo) S 
    GROUP BY S.Fruit,S.RegNo order by S.Fruit

输出:

    Name    RegNo   total    Fruit
   John     375       2     Apples
   John    375        1     Oranges
   John    375        10    Grapes
   John    375        2     Pear
   John    375        14    Mango

我想要这个输出

Name    RegNo   Apples Oranges   Grapes   Pear Mango    total   
John    375       2     1          10        2   14        29

那么如何得到这个结果呢?

2 个答案:

答案 0 :(得分:0)

您可以忽略Fruit子句中的GROUP BY字段,并使用条件聚合

SELECT S.RegNo,
       SUM(total) AS total,
       SUM(CASE WHEN s.Fruit = 'Apples' THEN total ELSE 0 END) AS Apples,
       SUM(CASE WHEN s.Fruit = 'Oranges' THEN total ELSE 0 END) AS Oranges,
       SUM(CASE WHEN s.Fruit = 'Grapes' THEN total ELSE 0 END) AS Grapes,
       SUM(CASE WHEN s.Fruit = 'Pear' THEN total ELSE 0 END) AS Pear,
       SUM(CASE WHEN s.Fruit = 'Mango' THEN total ELSE 0 END) AS Mango     
FROM (
   SELECT  RV.Fruit,RV.RegNo,COUNT(vv.Fruit) as total, RV.MS 
   from vv 
   inner join RV on vv.MID= RV.ID 
   inner join Re on RV.RID=Re.RID 
   WHERE Reg.SDate>='2016-04-0100:00:00.000' and 
         Reg.EDate<= '2016-04-30 23:59:59.000' and 
         Reg.Reg= 'UK' and RV.RegNo ='375' AND 
         Fruit <> '' 
   GROUP BY RV.Fruit,RV.RegNo) S 
GROUP BY S.RegNo 

答案 1 :(得分:0)

你可以使用PIVOT:

SELECT  *,
        [Apples]+[Oranges]+[Grapes]+[Pear]+[Mango] as total
FROM (
    SELECT 
       S.Fruit
       ,S.RegNo
       ,SUM(total) total 
    FROM (SELECT  
              RV.Fruit
              ,RV.RegNo
              ,COUNT(vv.Fruit) as total
              , RV.MS 
          from vv inner join RV on vv.MID= RV.ID 
          inner join Re on RV.RID=Re.RID 
          WHERE Reg.SDate>='2016-04-0100:00:00.000' and 
                Reg.EDate<= '2016-04-30 23:59:59.000'  and 
                Reg.Reg= 'UK' and RV.RegNo ='375' AND 
                Fruit <> '' 
          GROUP BY  RV.Fruit,RV.RegNo) S 
    GROUP BY S.Fruit,S.RegNo order by S.Fruit
    ) t
PIVOT (
    MAX(total) FOR Fruit IN ([Apples],[Oranges],[Grapes],[Pear],[Mango])
) pvt

如果有很多 fruits ,最好使用动态SQL。