2015-12-02 36 views
-2

任何機構都可以告訴我關於下面的情況。如何將當前年份和過去一年的值作爲列

我有事實表,其中有datekey,我有橋表,它有DatekeyPYdatekey(PYDatekey表示去年的值)。

當我想要當年的價值時,我加入FactTable.DateKey = BridgeTable.DateKey,對於去年的價值FactTable.DateKey=BridgeTable.PYDateKey

我正在寫兩個單獨的查詢做聯合所有以獲得這些值作爲行。

但現在我需要將這些值作爲列。請建議如何實現這一點。

+0

'INNER JOIN' - [使用內部聯接(https://technet.microsoft.com/fi-fi/library/ms190014(V = SQL.105)的.aspx) – Fabio

+1

而不是描述,只是具有期望的輸出結構的條目的後表結構。還顯示,你仍然做了什麼。 – Ajay2707

回答

0

您可以兩次加入FactTable以分別獲取以前和當前數據。

在BridgeTable中不需要Datekey和/或PYdatekey的情況下使用LEFT JOIN。

--Sample data 
CREATE TABLE BridgeTable (Datekey int, PYdatekey int) 
CREATE TABLE FactTable (datekey int, SomeField varchar(100)) 
INSERT INTO FactTable VALUES (1, 'A') 
INSERT INTO FactTable VALUES (2, 'B') 
INSERT INTO BridgeTable VALUES (1, 2) 
INSERT INTO BridgeTable VALUES (1, null) 
INSERT INTO BridgeTable VALUES (null, 2) 

--Query 
SELECT PreviousFacts.SomeField AS Previous_SomeField, CurrentFacts.SomeField AS Current_SomeField --Or whatever columns you need 
FROM BridgeTable 
LEFT JOIN FactTable PreviousFacts ON BridgeTable.PYdatekey = PreviousFacts.DateKey 
LEFT JOIN FactTable CurrentFacts ON BridgeTable.Datekey = CurrentFacts.DateKey 
相關問題