繁体   English   中英

MySQL:选择MAX值并分组

[英]MySQL: Selecting MAX value and grouping

这就是我现在查询中的内容:

+--------------------+-----------+------------+
| status             | entity_id | seconds    |
+--------------------+-----------+------------+
| Submitted          |       494 | 1352102400 |
| Accepted           |       494 | 1352275200 |
| In press/e-publish |       494 | 1352966400 |
| Rejected           |       520 | 1355817600 |
| Accepted           |       570 | 1352102400 |
+--------------------+-----------+------------+

我希望它看起来像:

+--------------------+-----------+------------+
| status             | entity_id | seconds    |
+--------------------+-----------+------------+
| In press/e-publish |       494 | 1352966400 |
| Rejected           |       520 | 1355817600 |
| Accepted           |       570 | 1352102400 |
+--------------------+-----------+------------+

在准SQL中:

SELECT status, entity_id, MAX(seconds) 
FROM foo
GROUP BY entity_id, seconds

上面的准SQL看起来正确,但是“状态”列值不对应于正确的行。 我得到类似下面的内容:

+--------------------+-----------+------------+
| status             | entity_id | seconds    |
+--------------------+-----------+------------+
| Submitted          |       494 | 1352966400 |
| Rejected           |       520 | 1355817600 |
| Accepted           |       570 | 1352102400 |
+--------------------+-----------+------------+

未经测试,但应如下所示:

SELECT status, entity_id, seconds
FROM entities E
WHERE E.seconds == (
  SELECT MAX(E2.seconds)
  FROM entities E2
  WHERE E2.entity_id = E.entity_id
)

(为您的问题设置一个SQLfiddle会给您一个更可靠的答案:p)

下面的查询将给出您期望的结果。

SELECT max(maxsec), status, entity_id from 
(SELECT status, entity_id, MAX(seconds)  as maxsec
FROM table1
GROUP BY entity_id,status) a GROUP BY entity_id

您的架构在这里创建。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM