2017-02-26 85 views
1

我對在數據庫中使用數據透視表非常感興趣,並且希望嘗試透視這一點。 任何幫助,將不勝感激。 (羅斯文數據庫)將第1列轉換爲標題,將第2列轉換爲行

我想要在TotalOrders上方樞軸姓氏。 最後的名字都在列1,總的訂單都在列2

lastname TotalOrders 
--------------------- 
Buchanan  42 

Callahan 104 

Davolio  123 

Dodsworth 43 

Fuller  96 

King   72 

Leverling 127 

Peacock  156 

Suyama  67 

/*試圖做的事:*/

[lastname] [Buchanan] [Callahan]... 

TotalOrders  42   104 ... 

/這是我到目前爲止所。/ [代碼]

SELECT lastname, COUNT(*) TotalOrders 
    FROM employees join orders 
    ON employees.employeeid = orders.employeeid 
    GROUP BY lastname 

PIVOT 
(
    COUNT(TotalOrders) 
    FOR lastname IN ([Buchanan], [Callahan], [Davolio], [Dodsworth] 
        ,[Fuller], [King], [Leverling], [Peacock], [Suyama]) 

) AS P; 

[/代碼]

回答

0

你接近。將連接查詢放入子查詢中,並在數據透視表中使用MAX(或MIN)。

select * 
from (
    SELECT lastname, COUNT(*) TotalOrders 
    FROM employees join orders 
    ON employees.employeeid = orders.employeeid 
    GROUP BY lastname 
) t 
PIVOT 
(
    MAX(TotalOrders) 
    FOR lastname IN ([Buchanan], [Callahan], [Davolio], [Dodsworth] 
        ,[Fuller], [King], [Leverling], [Peacock], [Suyama]) 

) AS P; 
+0

非常感謝GurV!你真棒!比你再次! –