2017-06-22 4 views
0

これは私が現在ピボットテーブルは2回ですか?

 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

"Breed"は "月"ではなく、 "Hugo"と "Lab"の間に明確な関係はありません。あなたは別のテーブルにすべての品種を表示するつもりですか? –

答えて

0

私は非常にあなたがそれを表示する方法に基づいて、その結果に選択を#TEMPテーブルにあなたの結果セットを保存してから行うことをお勧めします。あなたの最初のコラムが月を言いますが、そこに "繁殖"があるので、あなたが望む最終結果は混乱します。ヒューゴとマルコが1月に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) 
関連する問題