2010-08-24 198 views
0

請原諒我,如果這已被回答之前。Sql server 2000數據透視查詢

我正在尋找關於如何構建一個數據透視表或交叉表查詢的建議。

我有一個表,看起來喜歡這個

Vessel Date Inspector 
A  02/05/10 Morris 
B  05/20/10 Clouseau 
A  07/25/10 Gadget 

我需要的結果是這個樣子

Vessel Jan Feb  Mar  April May June July Aug Sept Oct Nov Dec 
    A   Morris        Gadget 
    B         Clouseau 

希望這是有道理的。我希望有人能給我一些建議或幫助讓我開始這個。

感謝

+0

如果您在同一個月和同一艘船上有兩名檢查員,應該會發生什麼情況? – Timwi 2010-08-24 04:56:09

+0

我想他們會想要一個逗號分隔的列表。但廣管局並不認爲會發生。 – gswanson 2010-08-26 00:04:01

回答

2
Select Vessel 
    , Min (Case When Month([Date]) = 1 Then Inspector End) As Jan 
    , Min (Case When Month([Date]) = 2 Then Inspector End) As Feb 
    , Min (Case When Month([Date]) = 3 Then Inspector End) As Mar 
    ... 
    , Min (Case When Month([Date]) = 12 Then Inspector End) As Dec 
From Table 
Group By Vessel 

你有靜態聲明列。應該指出的是,這隻會工作一年。如果您正在尋找的是動態列(月)生成,那麼嘗試在T-SQL中執行並不是正確的方法,因爲只能使用一些非常動態的SQL來完成。相反,您應該使用報告生成器或中間層組件來構建結果集。

0

我不認爲你需要爲這個樞軸 - 只需創建12子查詢,每個月一:

SELECT 
    Vessel, 
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=1) as Jan, 
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=2) as Feb, 
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=3) as Mar, 
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=4) as Apr, 
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=5) as May, 
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=6) as Jun, 
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=7) as Jul, 
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=8) as Aug, 
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=9) as Sep, 
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=10) as Oct, 
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=11) as Nov, 
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=12) as Dec 
FROM (
    SELECT DISTINCT(Vessel) FROM Stuff 
) Tbl 

您可以通過添加使這項工作對於任何特定一年AND YEAR(Date)=2010(例如)到12個子查詢中的每一個的結尾。