Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query -- how to find lowest 2 numbers

Tags:

sql

sql-server

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.

like image 475
Steven Deam Avatar asked Oct 29 '25 15:10

Steven Deam


1 Answers

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
like image 157
JohnHC Avatar answered Oct 31 '25 06:10

JohnHC