枢轴表两次?

时间:2017-06-22 09:20:20

标签: sql

这就是我目前正在展示的内容

       month           |   Breed|   Hugo | Marco |
       january 2017    |   Lab  |  4    |   5   |
       february 2017   |   Pug  |  7    |   3   |

是否有可能让表格连续显示品种 已经转动了桌子?

    month           |   Hugo | Marco |
    january 2017    |   4    |  5    |
    Breed           |   Lab  |  Pug  |

  SET @query ='SELECT * FROM(SELECT
      petstoreemployee.employeefirstname as employeefirstname
      ,sum(petID.breed) as breeds
      ,Format(date, ''MMMM-yyyy'') as Month
      ,breed as breed
  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''), breeds

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

exec sp_executesql @query

由于

1 个答案:

答案 0 :(得分:0)

我强烈建议您将结果集存储到#temp表中,然后根据您希望的结果对这些结果进行选择。你想要的最终结果是令人困惑的,因为你的第一列是月份,但你有“品种”。听起来你想要证明Hugo和Marco在1月份有4个Lab和5个哈巴狗。

如果是这种情况,最终结果应如下:

       Lab | Pug | Month
Hugo   4   |  0  | January 2017
Marco  0   |  5  | January 2017

你也使用SUM(petid.breed)但在你的例子里它是一个VARCHAR而不是数字。

你将不得不玩这个,但我希望这有助于你获得主要想法。

  SELECT
        petstoreemployee.employeefirstname as employeefirstname
       ,sum(petID.breed) as breeds
       ,Format(date, ''MMMM-yyyy'') as Month
       ,breed as breed
  INTO #PETTEMP
  FROM PETID A
  JOIN petstoreemployee b on  
       petID.petstoreemployeeID=petstoreemployee.petstoreemployeeID and
       petID.ProjectedPrjID=1 and (a.petID.date >= ''2017-01-01 
       00:00:00:000'' AND b.petID.date <= 
        '2017-12-31 00:00:00:000'')

  group by petstoreemployee.employeefirstname, Format(date,''yyyy''), 
  breeds

  --Do your select here from #pettemp
  -- your first select is your first column
  Select Month,petid from #pettemp
  -- join here for your second column
  join (select * from #pettemp)
  -- join here for your 3rd column
  join (select * from #pettemp)