我使用以下查询将结果作为
Select * from
(
Select M.MaterialName,L.LocationName,S.Balance,S.StockDate,ROW_NUMBER()
over(Partition by L.LocationName,M.MaterialName order by S.StockDate desc)RN from
StockRegister S join Locations L on S.LocationId=L.LocationId join
ElectricalProducts M on M.PartNo=S.PartNo
where S.StockDate<=convert(date,'01-02-2014',103) and
substring(S.PartNo,1,2)='01' and SUBSTRING(S.PartNo,9,3)='002'
)sr
结果是
Material Name Location Qty StockDate RN
Tube LightPhilips40W ShozhingaNal 200 2014-01-31 1
Tube LightPhilips40W Kottivakkam 200 2014-01-31 1
Tube LightPhilips40W Kottivakkam 150 2014-01-31 2
Tube LightPhilips40W MAChidambaramm 50 2014-01-31 1
从那里我必须得到唯一的最新条目如下
Material Name Location Qty StockDate RN
Tube LightPhilips40W ShozhingaNal 200 2014-01-31 1
Tube LightPhilips40W Kottivakkam 150 2014-01-31 2
Tube LightPhilips40W MAChidambaramm 50 2014-01-31 1
如何获得它?
答案 0 :(得分:1)
尝试这样
使用COUNT(*) OVER(Partition by L.LocationName,M.MaterialName ) CNT
来查找最新的行
SELECT * FROM
(
SELECT M.MaterialName,L.LocationName,S.Balance,S.StockDate,
ROW_NUMBER() OVER(Partition by L.LocationName,M.MaterialName order by S.StockDate DESC)RN
COUNT(*) OVER(Partition by L.LocationName,M.MaterialName ) CNT
FROM StockRegister S JOIN Locations L ON
S.LocationId=L.LocationId
JOIN ElectricalProducts M ON
M.PartNo=S.PartNo
WHERE S.StockDate <= convert(date,'01-02-2014',103) AND
SUBSTRING(S.PartNo,1,2)='01' AND
SUBSTRING(S.PartNo,9,3)='002'
)AS S
WHERE RN = CNT
或者尝试以下方法
由于您按行DESC
在RowNumber中订购StockDate,因此最新的RowNumber变为1.因此您可以按WHERE RN = 1
SELECT * FROM
(
SELECT M.MaterialName,L.LocationName,S.Balance,S.StockDate,
ROW_NUMBER() OVER(Partition by L.LocationName,M.MaterialName order by S.StockDate DESC)RN
FROM StockRegister S JOIN Locations L ON
S.LocationId=L.LocationId
JOIN ElectricalProducts M ON
M.PartNo=S.PartNo
WHERE S.StockDate <= convert(date,'01-02-2014',103) AND
SUBSTRING(S.PartNo,1,2)='01' AND
SUBSTRING(S.PartNo,9,3)='002'
)AS S WHERE RN = 1