1

这是我的桌子的TheTable样子

ColA  | ColB  | ColC
------+-------+------
abc   | 2005  | item7
abc   | 2010  | item3
def   | 2009  | item2
def   | 2010  | item4
def   | 2011  | item5
def   | 2012  | item1

我想写一个查询来返回这个结果:

ColA  | ColB  | ColC
------+-------+------
abc   | 2010  | item3
def   | 2012  | item1

我最终得到:

SELECT TheTable.ColA,TheTable.ColB,TheTable.ColC
FROM TheTable,(SELECT ColA a,MAX(ColB) b FROM TheTable GROUP BY ColA) t
WHERE t.a=TheTable.ColA AND t.b=TheTable.ColB

但我不确定这种嵌套查询是否非常有效。那么问题来了,有没有更好的方法呢?

4

1 回答 1

3
WITH OrderedTable AS
(
    SELECT ColA, ColB, ColC,
        ROW_NUMBER() OVER (PARTITION BY ColA ORDER BY ColB DESC) AS Row
    FROM TheTable
)
SELECT ColA, ColB, ColC FROM OrderedTable WHERE Row = 1
于 2012-06-13T11:17:14.630 回答