Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
I want to be able to pull the records with the earliest date 2011-02-06There were other records with this same customer and item number. I used this script to return the two above. select *from pricewhere end_dt > getdate()Now I need to add something so it only returns the record with the earliest date. I'm going to run this on a table that has many customer and item combinations.
[code]select a.cust_no, a.item_no, a.start_dt, a.end_dt, a.pricefrom ( select p.*, row_number() over (partition by p.cust_no, p.item_no order by p.start_dt) rn from price p where end_dt > GETDATE() ) awhere a.rn = 1[/code]No amount of belief makes something a fact. -James Randi
gbritton
Master Smack Fu Yak Hacker
2780 Posts
Posted - 2014-11-12 : 10:51:07
Or:
SELECT p.cust_no, p.item_no, p.end_dt, p.price, p.start_dtFROM ( SELECT p.cust_no, p.item_no, p.end_dt, p.price, p.start_dt, min(p.start_dt) over(PARTITION BY p.cust_no, p.item_no) as min_start_dt FROM price p WHERE p.end_dt > getdate() ) pWHERE p.start_dt = p.min_start_dt