2014-02-23 84 views
2

我需要爲表中的每列選取前2個不同的值。前2個值是根據日期字段選擇的。爲每列獲取前2個不同的值

Table A 
status id Col1 Col2  Col3  Date 
A  1  Name1 Name4  Name6  1/18/14 5:54 
B  1  Name1 Name5  Name6  1/18/14 5:54 
B  1  Name2 Name6  Name6  1/12/14 5:54 
B  1  Name2 Name6  Name7  10/11/13 3:34 

結果:

status id Col1 Col2  Col3 
A  1  Name1 Name4  Name6 
B  1  Name2 Name5  Name7 
+0

哪個SQL您使用的?對於MySQL,至少,「DISTINCT」只返回不同的行,不能像這樣混合行。 – andrewtweber

+0

@andrewtweber - 鑑於'DISTINCT'是標準的一部分,它在_all_實現中的表現更好。到OP - 你在查詢中到目前爲止已經嘗試過了什麼?處理'Col1' - 'Col3'會變成_painful_ - 這是從我們可以使用的不同表中得出的(給出您使用的示例數據似乎是相關的)。那麼'id'呢?據推測,你在該列中有多個值...並且是'date'的某種時間戳?是的,我們仍然需要SQL供應商和版本。 –

+0

@ Clockwork-Muse我不知道有一個標準,很酷。 – andrewtweber

回答

0

如果用於SQL Server,你可以嘗試:

;with cte as(

select *,row_number() over(partition by status order by Date desc) as rn from table 
) 

select status,id,col1,col2,col3 from cte where rn=1 

See Demo

相關問題