2017-06-21 63 views
0

我能得到我的表顯示像這樣使用數據透視表動態集團通過 - 鮮明的數據透視表

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 
+0

添加GROUP BY月和使用SUM爲列雨果和Marco –

+0

選擇月,MAX([雨果])[雨果],MAX([馬可])[馬科] FROM#表11 組按月 – Chanukya

+0

我確實按月分組? **格式(日期,''yyyy'')** @EstebanP。 – vanillacoke9191

回答

0

嘗試在分組之前將選擇「源」放入嵌套選擇子查詢中。像這樣的東西。

  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 
+0

它在''附近給我一個不正確的語法錯誤。 ..我似乎無法發現它:( – vanillacoke9191

+0

@ vanillacoke9191嗯,它似乎是在加入部分...根據您的腳本。我認爲PetID是一張桌子,我更新了腳本,希望它的作品。 –