我有一张包含这些记录的表格:
id code date
----- ------ -----
1 12 2016-01-01
2 12 2016-01-02
3 17 2016-01-03
4 12 2016-01-04
5 17 2016-01-05
6 17 2016-01-06
7 17 2016-01-07
我使用此查询:
SELECT `id`, `code`, `date`, COUNT(*) AS total
FROM `foo`
GROUP BY (code)
ORDER BY (id) DESC
我得到了这个:
id code date total
----- ------ ------ ------
3 17 2016-01-03 4
1 12 2016-01-01 3
但我需要显示:
id code date total
----- ------ ------ ------
7 17 2016-01-07 4
4 12 2016-01-04 3
有可能吗?非常感谢你。
答案 0 :(得分:1)
使用MAX
功能:
SELECT
MAX(id) AS id,
code,
MAX(date) AS date,
COUNT(*) AS total
FROM foo
GROUP BY code
ORDER BY MAX(id) DESC;