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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Get minimum start date

Author  Topic 

Vack
Aged Yak Warrior

530 Posts

Posted - 2014-11-12 : 10:08:06
I'm looking at the following Records:


cust_no item_no start_dt end_dt price
1060 2931 2011-02-06 9999-12-31 1.23
1060 2931 2011-04-18 9999-12-31 2.00




I want to be able to pull the records with the earliest date 2011-02-06
There were other records with this same customer and item number. I used this script to return the two above.

select *
from price
where 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.

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-11-12 : 10:30:47
SELECT p.cust_no, p.item_no, p.start_dt, p.end_dt, p.price
FROM price p
CROSS APPLY (
SELECT min(p1.start_dt) start_dt
FROM @price p1
WHERE p.cust_no = p1.cust_no
AND p.item_no = p1.item_no
) p1
WHERE p.end_dt > getdate()
AND p.start_dt = p1.start_dt
Go to Top of Page

Bustaz Kool
Master Smack Fu Yak Hacker

1834 Posts

Posted - 2014-11-12 : 10:37:59
[code]select
a.cust_no,
a.item_no,
a.start_dt,
a.end_dt,
a.price
from (
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()
) a
where
a.rn = 1[/code]


No amount of belief makes something a fact. -James Randi
Go to Top of Page

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_dt
FROM (
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()
) p
WHERE p.start_dt = p.min_start_dt
Go to Top of Page
   

- Advertisement -