我有一张这样的表:
+-------------------------------+---------------+---------------------+
| color | code | date |
+-------------------------------+---------------+---------------------+
| red | 300 | 2017-06-23 11:44:14 |
| red | 600 | 2017-06-23 11:37:14 |
| green | 200 | 2017-06-23 09:08:59 |
| green | 200 | 2017-06-23 09:06:59 |
| yellow | 0 | 2017-06-21 09:23:43 |
| blue | 100 | 2017-06-21 09:13:36 |
| blue | 105 | 2017-06-21 09:12:36 |
| red | 200 | 2017-06-21 09:11:05 |
| green | 200 | 2017-06-21 09:09:46 |
| yellow | 900 | 2017-06-21 09:01:04 |
| blue | 400 | 2017-06-21 08:50:50 |
| blue | 400 | 2017-06-21 08:50:30 |
| red | 700 | 2017-06-21 08:49:52 |
| red | 800 | 2017-06-21 08:49:03 |
| green | 500 | 2017-06-20 20:15:29 |
| yellow | 200 | 2017-06-20 19:31:47 |
| blue | 300 | 2017-06-20 19:15:02 |
| blue | 300 | 2017-06-19 19:20:02 |
+-------------------------------+---------------+---------------------+
我需要一个查询,它会创建一个表格,显示颜色列中每种颜色的总量,并显示每种颜色的最新代码和日期。
我到目前为止最接近的是这个查询:
SELECT color,
max(code) AS code,
max(date) AS date,
count(*) AS count
FROM checks
GROUP BY color
ORDER BY count DESC LIMIT 12;
这几乎是完美的,除了代码列显示最高编号而不是最新代码。所以黄色代码应该是900,因为它应该是0,因为0是最新的。
上述查询的示例表:
+---------------------------+---------------+---------------------+-------+
| color | code | date | count |
+---------------------------+---------------+---------------------+-------+
| blue | 400 | 2017-06-21 09:13:36 | 6 |
| red | 800 | 2017-06-23 11:44:14 | 5 |
| green | 500 | 2017-06-23 09:08:59 | 4 |
| yellow | 900 | 2017-06-21 09:23:43 | 3 |
+---------------------------+---------------+---------------------+-------+
如果我将max(code)
更改为code
,则会获得第一个代码,因此黄色代码将为200.
我需要结果表看起来像这样:
+---------------------------+---------------+---------------------+-------+
| color | code | date | count |
+---------------------------+---------------+---------------------+-------+
| blue | 100 | 2017-06-21 09:13:36 | 6 |
| red | 300 | 2017-06-23 11:44:14 | 5 |
| green | 200 | 2017-06-23 09:08:59 | 4 |
| yellow | 0 | 2017-06-21 09:23:43 | 3 |
+---------------------------+---------------+---------------------+-------+
谢谢:)
答案 0 :(得分:2)
这样的事情:
select t.*, the_table.code from the_table
inner join
(select color, count(*), max(date) as maxdate from the_table group by color)t
on the_table.color = t.color and the_table.date = t.maxdate