2011-04-19 66 views
0

我正在尝试做类似Select the 3 most recent records where the values of one column are distinct的工作,但带了一个计数,这意味着我需要保留该组。MYSQL Group Gy订购Count?

使用相同的例子:

id  time  text  otheridentifier 
------------------------------------------- 
1  6   apple  4 
2  7   orange 4 
3  8   banana 3 
4  9   pear  3 
5  10  grape  2 

SELECT *, COUNT(*) FROM `table` GROUP BY (`otheridentifier`) ORDER BY `time` DESC LIMIT 3 

将返回5号,3,1与适当的罪状,但我想5,4,2

在该职位的解决方案是

SELECT * FROM 'table' WHERE 'id' = (SELECT 'id' 
FROM 'table' as 'alt' 
WHERE 'alt'.'otheridentifier' = 'table'.'otheridentifier' 
ORDER BY 'time' DESC 
LIMIT 1) ORDER BY 'time' DESC LIMIT 3 

,但我看不出如何抓住计数,因为我需要一个分组有:我得到ERROR 1140 (42000): Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause如果我添加COUNT(*),以那开始。

+0

您的sql中没有任何组。你想要计算什么? – 2011-04-19 19:59:14

+0

我在第一个查询中做了:我试图计算由'otheridentifier'分组的项目数。 – aaronwinborn 2011-04-19 20:04:48

回答

0
SELECT *, COUNT(*) 
FROM `table` 
GROUP BY (`otheridentifier`) 
ORDER BY COUNT(*) DESC LIMIT 3 
^^^^^^^^^^^^^^^^^ 

只需更改order by子句。排序在分组/聚合完成后完成,因此您可以按这些聚合函数的结果进行排序。

+0

,似乎并不能保留我的'时间'命令。 – aaronwinborn 2011-04-19 20:11:30

+0

所以你想要在任何组的最后记录? – 2011-04-19 20:14:46

+0

是的,这就是我想要的!我希望记录与上次匹配,按其他标识分组,并计算该组中的所有记录。 – aaronwinborn 2011-04-19 20:30:32