如何查找查询列的最小值

时间:2014-12-02 00:02:44

标签: mysql sql

如何找到查询列的最小值?

我的表格X的数据如下所示:

(id, something, userId, something) values

('R001','something','U0006','something'),
('R002','something','U0014','something'),
('R001','something','U0006','something'),
('R002','something','U0015','something'),
('R003','something','U0003','something'),
('R001','something','U0014','something'),
('R001','something','U0002','something');

我的查询,如下所示:

SELECT DISTINCT userId, COUNT( id ) AS count
FROM X
GROUP BY userId
ORDER BY count DESC 

并且此查询返回:

userId  count
U0006   2
U0014   2
U0002   1
U0003   1
U0015   1

如何在查询中获取最小值,请记住有多个最小值?

我想从查询中获得的回报如下所示:

userId
U0002
U0003
U0015

提前谢谢:)

1 个答案:

答案 0 :(得分:0)

您可以使用having子句执行此操作:

SELECT userId, COUNT( id ) AS count
FROM X
GROUP BY userId
HAVING COUNT(id) = (SELECT MIN(cnt)
                    FROM (SELECT COUNT(id) as cnt
                          FROM X
                          GROUP BY userId
                         ) xx
                   );

select distinctgroup by一起使用几乎总是多余的。