我很確定我需要一個樞軸來做到這一點,但不能完全弄清楚。 (SQL福利局)如何編寫一個數據透視表來顯示每年的列記錄?
我的數據是這樣的:
ID CompanyID Year Revenue Expenses
1 0003 2011 12000 4000
2 0003 2010 9000 6000
3 0003 2009 7000 9000
4 0010 2011 134300 34000
5 0010 2010 43000 46000
6 0010 2009 73000 39000
我可以使用透視來顯示這個表是這樣的:
CompanyID 2011-Revenue 2010-Revenue 2009-Revenue 2011-Expenses 2010-Expenses 2009-Expenses
0003 12000 9000 7000 4000 6000 9000
0010 134300 43000 73000 34000 46000 39000
這裏是我迄今爲止...
SELECT P1.*
FROM (SELECT [CompanyID]
,CASE P.[Year] WHEN 2011 THEN P.[Revenue] ELSE NULL END AS '2011-Revenue'
,CASE P.[Year] WHEN 2010 THEN P.[Revenue] ELSE NULL END AS '2010-Revenue'
FROM tblRecords P WHERE P.[CompanyID] = @companyID GROUP BY CompanyID, [Year], [Revenue]) AS P1
這是返回:
CompanyID 2011-Revenue 2010-Revenue
0003 12000 NULL
0003 NULL 9000
個
幾個問題,我的結果...
的有兩條記錄爲CompanyID 0003我想它想組進一個記錄
我只能選擇1家公司在時間,我需要選擇多個。我試圖
FROM tblRecords P WHERE P.[CompanyID] IN (@CompanyIDs) GROUP BY CompanyID, [Year], [Revenue]) AS P1
凡
@CompanyIDs
是一個字符串像'0003, 0010'
- 它並沒有失敗,但換來的只是一個空表頭和任何數據..
任何幫助,將不勝感激..或讓我知道如果我誤解樞軸?
非常感謝!
托馬斯
編輯:使用Microsoft SQL Server Management Studio中2005速成
更新2:我已經想通了連接表的詳細信息,但我還需要能夠在該CompanyIDs爲越過一個逗號分隔的字符串..任何幫助,將不勝感激。
vvvvvvvv我已經想通了下面這個(會後,一旦所有工作)vvvvvvv
更新:它看起來像什麼魯本提出去上班,但是我剛剛決定我需要多一點的功能對此...我能加入這個與另一個表有頭
CompanyID CompanyName CompanyAddress 2011-Revenue 2010-Revenue
如果公司名稱和公司地址來自另一個表(tblCompanyDetails)
我使用已經試過:
SELECT *
FROM
(
SELECT CompanyID, tblCompanyDetails.CompanyName, tblCompanyDetails.CompanyAddress, CAST(YEAR AS varchar) + ' - Revenue' Type,
Revenue Value FROM tblRecords
FROM tblRecords INNER JOIN tblCompanyDetails ON tblRecords.CompanyID = tblCompanyDetails.CompanyID
UNION ALL
SELECT CompanyID, tblCompanyDetails.CompanyName, tblCompanyDetails.CompanyAddress, CAST(YEAR AS varchar) + ' - Expenses' Type,
Expenses Value FROM tblRecords
FROM tblRecords INNER JOIN tblCompanyDetails ON tblRecords.CompanyID = tblCompanyDetails.CompanyID
) src
PIVOT
(
SUM(Value) for [Type] in
([2011 - Revenue], [2010 - Revenue], [2009 - Revenue],
[2011 - Expenses], [2010 - Expenses], [2009 - Expenses]
)
) pvt
WHERE CompanyID = @CompanyID
我得到的錯誤:
Msg 1038, Level 15, State 4, Procedure spCompare, Line 10
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Add a name or single space as the alias name.
microsoft sql server? – 2011-12-19 03:03:40
對不起,我包含TSQL標籤,但可能更具體。 Micorsoft SQL Server 2005 – tsdexter 2011-12-19 03:04:48
我覺得通常在服務器上只執行GROUP BY更靈活,然後在客戶端應用程序中交叉結果。 – 2011-12-19 08:56:06