2015-10-16 69 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作爲例子。然後你可以在你的系統上試用它,你會明白我的意思。 –