简体   繁体   中英

Sql server 2008 - how to get records by the earliest dates

table is rpt

custID    dates         stores
111089    2015-09-28    103
111089    2015-06-19    119
111089    2015-10-11    106
555555    2015-05-02    103
555555    2015-08-21    125
555555    2015-09-20    125
123456    2015-01-01    119
123456    2015-05-13    116
123456    2015-09-15    120
123456    2015-08-29    115

result should be

custID    dates         store
111089    2015-06-19    119
555555    2015-05-02    103
123456    2015-01-01    119

the table is a very big table and I need all custID and store with the earliest date. like the result above.  
only one row per custID

You can do this with a windowed function with a PARTITION on the CustID and ordering by dates:

;With Cte As
(
    Select  *, Row_Number() Over (Partition By CustID Order By Dates Asc) As Row_Number
    From    rpt
)
Select  custID, dates, stores
From    Cte
Where   Row_Number = 1
SELECT rpt.custid, rpt.date, rpt2.stores
FROM (select r.custid, min(r.DATE) as 'Date'
      from rpt r
      group by r.custid) rpt

left join (select r.custid, r.DATE, r.stores
           from rpt r) rpt2 on rpt2.custid = rpt.custid and rpt2.date = rpt.date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM