2015-10-16 65 views
0
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
+0

看一看这个类似的[问题](http://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group)。 –

回答

3

您可以在客户ID一个PARTITION和排序按日期与窗口函数做到这一点:

;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 
+0

太好了。惊人。它的作品像一个魅力。非常感谢你。你为我节省了很多时间。 rpt是同一张表上的一个选择,所以我只是将选择放在那里,它只是工作。简直太神奇了。再次感谢..... –

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 
+1

这将产生正确的结果,但过于复杂,性能将受到影响,因为您必须用相同的数据两次查询相同的数据。 –

+0

通过创建/填充cte然后查询它,数据被击中两次,对吗?我对性能差异感到好奇......如果你能详细说明,将不胜感激。 –

+1

因为cte不会在第二个select语句所在的位置导致第二个表扫描。我将以一个sqlfiddle作为例子。然后你可以在你的系统上试用它,你会明白我的意思。 –

相关问题