如何在选择另一列的最大值时选择*并按列分组?

时间:2016-02-16 09:36:29

标签: sql-server-2012

fruitID|fruitName     |dateAge
23     |Rotten Apple  |2
23     |Old Apple     |3 
23     |New Apple     |4
12     |Rotten Banana |4
12     |Old Banana    |5
12     |New Banana    |6
8      |New Mango     |6
7      |Rotten Grapes |5

expected result:

fruitID|fruitName     |dateAge
23     |New Apple     |4
12     |New Banana    |6
8      |New Mango     |6
7      |Rotten Grapes |5

我希望结果具有最新收获日期的fruitID

1 个答案:

答案 0 :(得分:1)

select a.fruitID, max(a.dateHarvest ) as dt, 
(select fruitName from test b where a.fruitID=b.fruitID and b.dateHarvest=max(a.dateHarvest )) 
as name from test a
group by a.fruitID
order by fruitID desc 

应该做的伎俩(tablew名称是测试)

编辑:如果您使用分组依据,则不能使用*。

这是2008R2,而不是2012R2 enter image description here