如何为给定的user_id集合获取每个组的最后记录(最小值)?

时间:2016-10-07 05:55:57

标签: mysql sql sql-server sql-server-2008

我的数据如下表所示:

表名 - item_quote

id  user_id   latestprice
1     10        5000
2     10        12000
3     10        5600
4     20        1000
5     20        100
6     30        2560
7     30        256

现在我写了以下查询:

select * from item_quote where user_id in (10,20,30) order by id desc limit 3

所以它会给我以下数据:

id  user_id   latestprice
1     10        5000
2     10        12000
3     10        5600

但我想要以下输出:

id  user_id   latestprice
7     30        256
5     20        100
1     10        5000

我通过以下查询获得解决方案:

select * from (SELECT * FROM `item_quote` where user_id in (10,20,30) ORDER BY id desc  ) as t group by user_id

2 个答案:

答案 0 :(得分:0)

您需要在此处使用GROUP BY语句

SELECT MAX(id),latestprice FROM item_quote WHERE id IN ( SELECT MAX(id) FROM test GROUP BY user_id ) ORDER By id DESC

答案 1 :(得分:-1)

以下查询将为您提供所需的输出:

 SELECT * FROM (SELECT * FROM item_quote ORDER BY latestprice ) AS Temp 
 GROUP BY user_id DESC;