这是我的表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
但我不确定这种嵌套查询是非常有效的。所以问题是,有更好的方法吗?
答案 0 :(得分: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