I need to create a query that finds the lowest 2 values for each unique item in a table -- I am trying to find the first 2 shipments of each item.
So if the shipping table has:
ID ---- Date --- PartID
1 ---- 1/1 ---- 1
2 ---- 1/2 ---- 2
3 ---- 1/2 ---- 1
4 ---- 1/3 ---- 1
I would want rows 1, 2, and 3 returned as they are the first and second shipment of each item.
I can create a query that gets the lowest 2 values:
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))
but when I add in other information I only get the lowest for each item, not both:
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
-- returns only 1 row for each AddressID, not the 2 records that I would want.
If SQL server, use a CTE and a 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With