Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 使用where和group by选择列值最小的行_Mysql_Sql_Greatest N Per Group - Fatal编程技术网

Mysql 使用where和group by选择列值最小的行

Mysql 使用where和group by选择列值最小的行,mysql,sql,greatest-n-per-group,Mysql,Sql,Greatest N Per Group,样本表: 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

样本表:

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
我想选择
user\u id=100
grade\u id
分组的行,前提是其
时间戳对于特定
grade\u id
最小

因此,从上表中可以看出:

第1行,因为它的
时间戳
对于等级id(1001)的值是最小的

但不是第2行,因为我只想为一个特定的等级id

也不是第6行,因为特定的等级id
对用户id 105的值最小

我尝试了一些太基本的东西,显然不值得发布


谢谢

您可以尝试嵌套查询:

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;  

在这种情况下,嵌套查询将为您提供每个特定“grade\u id”的最小时间戳,您可以在WHERE过滤器中使用它。

您使用的是什么数据库?某些数据库具有用于此目的的内置函数,其他数据库则要求您为其编写自己的SQL。的可能重复项
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 ;