Sql server 2008 - 如何在最早的日期获取记录

时间:2015-10-16 18:23:07

标签: sql sql-server sql-server-2008 sql-server-2008-r2

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

2 个答案:

答案 0 :(得分:3)

您可以使用带有PARTITION在CustID上的窗口函数并按日期排序来执行此操作:

;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

答案 1 :(得分:2)

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