2017-06-22 97 views
0

這是我目前顯示樞軸表兩次?

 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

我會強烈建議你根據你想要的顯示存儲你的結果集到一個#TEMP表,然後做一個選擇這些結果。你想要的最終結果是令人困惑的,因爲你的第一個專欄說月份,但你有「繁殖」。聽起來你想表明,雨果和馬可一月份有4個實驗室和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)