[英]Select a row with least value of a column using where and group by
Sample table: 样表:
id------user_id------grade_id------time_stamp
1---------100----------1001---------2013-08-29 15:07:38
2---------101----------1002---------2013-08-29 16:07:38
3---------100----------1001---------2013-08-29 17:07:38
4---------102----------1003---------2013-08-29 18:07:38
5---------103----------1004---------2013-08-29 19:07:38
6---------105----------1002---------2013-08-29 20:07:38
6---------100----------1002---------2013-08-29 21:07:38
I want to select rows whose user_id = 100
group by grade_id
only if its time_stamp is least
for that particular grade_id
. 我只想选择
user_id = 100
按grade_id
分组的行, grade_id
是其time_stamp is least
于该特定grade_id
。
so, from the above table, it should be: 因此,从上表中可以看出:
row 1 because its time_stamp
is least for that value of grade_id(1001) 第1行,因为它的
time_stamp
至少是那个grade_id(1001)的值
but not row 2 because I only want 1 row for a particular grade_id 但不排第2行,因为对于特定的grade_id我只希望排1行
also not row 6 because that particular grade_id has least value for user_id 105
. 也不是第6行,因为该特定的grade_id
has least value for user_id 105
。
I tried few things, which are too basic and obviously not worth posting. 我尝试了一些基本的东西,显然不值得发布。
Thank You 谢谢
You could try nested queries: 您可以尝试嵌套查询:
SELECT grade_id, COUNT(grade_id) FROM SAMPLE_TABLE ST WHERE time_stamp = (SELECT MIN(time_stamp) FROM SAMPLE_TABLE STT WHERE STT.grade_id = ST.grade_id) AND user_id = 100 GROUP BY grade_id;
In this case, the nested query will give you the minimun timestamp for each specific 'grade_id' and you can use it in your WHERE filter. 在这种情况下,嵌套查询将为您提供每个特定“ grade_id”的最小时间戳,您可以在WHERE过滤器中使用它。
SELECT t.*
FROM tableX AS t
JOIN
( SELECT grade_id, MIN(time_stamp) AS time_stamp
FROM tableX
GROUP BY grade_id
) AS g
ON g.grade_id = t.grade_id
AND g.time_stamp = t.time_stamp
WHERE t.user_id = 100 ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.