對於給定的「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
只需在Where子句中添加2個AND語句? – Hoh
什麼是RowNumber列?您似乎沒有在查詢中的任何地方使用它。 –