分组 - 不同的数据透视表

时间:2017-06-21 06:09:14

标签: sql sql-server

我能够使用数据透视表动态地显示这样的表格

month           |   Hugo | Marco |
january 2017    |   5    |       |
february 2017   |   3    |       |
january 2017    |        |  4    |
february 2017   |        |  7    |

我如何将月份分组显示为这样?任何帮助将不胜感激。感谢。

month           |   Hugo | Marco |
january 2017    |   5    |  4    |
february 2017   |   3    |  7    |

SET @query ='SELECT * FROM(SELECT
          petstoreemployee.employeefirstname as employeefirstname
          ,sum(petID.breed) as breeds
          ,Format(date, ''MMMM-yyyy'') as Month

   FROM
          petID, petstoreemployee
   WHERE
          petID.petstoreemployeeID=petstoreemployee.petstoreemployeeID and
          petID.ProjectedPrjID=1
          and
          (petID.date >= ''2017-01-01 00:00:00:000'' AND petID.date <= 
  ''2017-12-31 00:00:00:000'')
   group by petstoreemployee.employeefirstname, Format(date,''yyyy'')

)
as d
PIVOT(
   avg(breeds)
   for employeefirstname
   IN (' + @pet + ')
) as p'

exec sp_executesql @query

1 个答案:

答案 0 :(得分:0)

尝试选择&#34;来源&#34;在分组之前进入嵌套的选择子查询。像这样的东西。

          SET @query ='SELECT [month],' + @pet + ' FROM(

                    SELECT t.employeefirstname,
                           SUM(t.breed) AS breeds,
                           t.[Month]
                    FROM (
                             SELECT     petstoreemployee.employeefirstname AS employeefirstname ,
                                        petID.breed,
                                        FORMAT(date, ''MMMM-yyyy'') AS Month
                              FROM      petID 
                                        JOIN  petstoreemployee ON
                                        petID.petstoreemployeeID = petstoreemployee.petstoreemployeeID
                              WHERE     petID.ProjectedPrjID = 1
                                        AND ( petID.date >= ''2017-01-01 00:00:00:000''
                                              AND petID.date <= ''2017-12-31 00:00:00:000''
                                            )

                            )T
                             GROUP BY  t.employeefirstname,t.[Month]
            )
            as d
            PIVOT(
               avg(breeds)
               for employeefirstname
               IN (' + @pet + ')
            ) as p'

            exec sp_executesql @query