我需要创建一个查询,查找表中每个唯一项的最低2个值 - 我正在尝试查找每个项的前2个货件.
因此,如果发货表有:
ID ---- Date --- PartID
1 ---- 1/1 ---- 1
2 ---- 1/2 ---- 2
3 ---- 1/2 ---- 1
4 ---- 1/3 ---- 1
Run Code Online (Sandbox Code Playgroud)
我希望返回第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))
Run Code Online (Sandbox Code Playgroud)
但是当我添加其他信息时,我只获得每个项目的最低值,而不是两者:
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
Run Code Online (Sandbox Code Playgroud)
- 每个AddressID只返回1行,而不是我想要的2行.
执行此操作的常规方法是使用窗口函数,在这种情况下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;
Run Code Online (Sandbox Code Playgroud)
如果是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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |