MSSQL:如何从另一个表中获取多个值

时间:2014-02-27 08:51:11

标签: sql sql-server database

对于给定的“CustomerId”,我需要从另一个表中的列(“CompanySales”)中获取4个相关值。

我加入了这两个表,并通过下面的查询,设法从另一个表的列中获取2个“CompanySales”值。

我该怎么做才能得到4个值(CompanySales“= 1,2,3和4我需要WeekNumber

这是我必须为“CompanySales”= 1和2确保“Weeknumber”的SQL查询:

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

1 个答案:

答案 0 :(得分:0)

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