2014-02-27 95 views
0

對於給定的「CustomerId」,我需要從另一個表中的列(「CompanySales」)中獲取4個相關值。MSSQL:如何從另一個表中獲取多個值

我已經加入了這兩個表,並在下面的查詢中設法從另一個表中的列中獲得2「CompanySales」值。

我怎麼做這讓4個值(我需要CompanySales爲「WeekNumber」 = 1,2,3和4)

這是SQL查詢我要安全「CompanySales」爲「Weeknumber」 = 1和2:

Declare @TempTable1 table 
(
    CustomerID INT, 
    CustomerName Varchar (50), 
    CompanySales DEC (8,2), 
    WeekNumber INT 
) 
INSERT INTO @TempTable1 ("CustomerID","CustomerName", "WeekNumber") 
SELECT  Customer.CustomerID, Customer.CustomerName, Company.WeekNumber, company.Sales 
FROM   Customer INNER JOIN 
        Company ON Customer.CustomerID = Company.CustomerID; 
With tblDifference as 
(
Select Row_Number() OVER (Order by WeekNumber) as RowNumber,CustomerID,CustomerName, companysales, WeekNumber from @TempTable1 
) 
Select Top (50) cur.CustomerID, Cur.CustomerName, Cur.WeekNumber as CurrentWeek, Prv.WeekNumber as PreviousWeek, Cur.CompanySales as CurrentSales,  Prv.CompanySales as PreviousSales, CAST(((Cur.CompanySales-Prv.CompanySales)/Prv.CompanySales)*100 As Decimal(8,2)) as PercentChange from 
tblDifference Cur Left Outer Join tblDifference Prv 
On Cur.CustomerID=Prv.CustomerID 

Where cur.WeekNumber = 1 AND prv.WeekNumber = 2 
Order BY PercentChange ASC 
+0

只需在Where子句中添加2個AND語句? – Hoh

+0

什麼是RowNumber列?您似乎沒有在查詢中的任何地方使用它。 –

回答

0

如何在cur.WeekNumber之間添加1到4之間?

+0

謝謝Mandar,我不完全理解你的建議。你能澄清嗎?也許提供一些建議的語法來嘗試?謝謝! – Eoghanon

+0

如果我理解正確,您需要第1到第4周的數據。正如其他答案中的建議,請再添加2個輪,或者如果您的週數始終是順序的,請嘗試將where和1之間的cur.WeekNumber作爲Where子句。 –

相關問題