Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.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 透视表两次?_Sql - Fatal编程技术网

Sql 透视表两次?

Sql 透视表两次?,sql,Sql,这就是我目前正在展示的内容 month | Breed| Hugo | Marco | january 2017 | Lab | 4 | 5 | february 2017 | Pug | 7 | 3 | 是否有可能让表格显示一行中的品种,而不是之后 已经在旋转桌子了吗 month | Hugo | Marco | january

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

       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

谢谢

我强烈建议您将结果集存储到临时表中,然后根据您希望的显示方式对这些结果进行选择。你想要的最终结果是令人困惑的,因为你的第一栏写的是月份,但你有繁殖。听起来你想证明雨果和马可一月份有4个实验室和5个哈巴狗

如果是这种情况,最终结果应该是这样的:

       Lab | Pug | Month
Hugo   4   |  0  | January 2017
Marco  0   |  5  | January 2017
您也在使用SUMpetid.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)

你想要的产量毫无意义-品种不是一个月,Hugo和Lab之间没有明显的关系。你打算在单独的表格中显示所有品种吗?