我需要创建一个查询,查找表中每个唯一项目的最低2个值 - 我正在尝试查找每个项目的前2个货件。
因此,如果发货表有:
ID ---- Date --- PartID
1 ---- 1/1 ---- 1
2 ---- 1/2 ---- 2
3 ---- 1/2 ---- 1
4 ---- 1/3 ---- 1
我希望返回第1,2和3行,因为它们是每个项目的第一次和第二次发货。
我可以创建一个获得最低2个值的查询:
Select Min(ShipmentID) as SID
from dbo.Shipment
UNION
Select Min(ShipmentID) as SID
from dbo.Shipment
where (ShipmentID >
(Select Min(ShipmentID)
from dbo.Shipment))
但是当我添加其他信息时,我只获得每个项目的最低值,而不是两者:
Select Min(ShipmentID) as SID, AddressIDBilling
from dbo.Shipment
Group by AddressIDBilling
UNION
Select Min(ShipmentID) as SID, AddressIDBilling
from dbo.Shipment
where (ShipmentID >
(Select Min(ShipmentID)
from dbo.Shipment))
Group By AddressIDBilling
Order By AddressIDBilling
- 每个AddressID只返回1行,而不是我想要的2行。
答案 0 :(得分:6)
执行此操作的常规方法是使用窗口函数,在本例中为rank()
或row_number()
(取决于您希望如何处理关系):
select s.*
from (select s.*,
row_number() over (partition by partid order by date asc) as seqnum
from dbo.shipment s
) s
where seqnum <= 2;
答案 1 :(得分:6)
如果使用SQL Server,请使用CTE和row_number()
with CTE as
(
select PartID, Date, row_number() over(partition by PartID order by Date) as PartOrd
from MyTable
)
select PartID, Date, PartOrd
from CTE
where PartOrd <=2