2010-04-30 73 views

回答

5

此:

WITH q AS 
     (
     SELECT *, ROW_NUMBER() OVER (PARTITION BY field2 ORDER BY field3 DESC) AS rn 
     FROM table1 
     ) 
SELECT * 
FROM q 
WHERE rn = 1 

或該:

SELECT q.* 
FROM (
     SELECT DISTINCT field2 
     FROM table1 
     ) qo 
CROSS APPLY 
     (
     SELECT TOP 1 * 
     FROM table1 t 
     WHERE t.field2 = qo.field2 
     ORDER BY 
       t.field3 DESC 
     ) q 

根據field2基數,該第一或第二查詢可以是更有效的。

請參閱本文的詳細信息:

+0

感謝Quassnoi。第一個返回一個額外的「rn」列,請編輯它如下:...... WITH q AS(SELECT *,ROW_NUMBER()OVER(PARTITION BY field2 ORDER BY field3 DESC)AS rn FROM table1)SELECT Field1 ,Field2,Field3,Field4 FROM q WHERE rn = 1 ......但第二個很棒,文章也很棒。非常感謝。 – 2010-04-30 19:18:51

相關問題