15

有一个包含 item_id 和 color_id 的产品表。我正在尝试获取具有最多非空实例的 color_id 。

这失败了:

SELECT color_id 
  FROM products 
 WHERE item_id=1234 
 GROUP BY item_id 
HAVING MAX(COUNT(color_id))

Invalid use of group function

SELECT color_id, COUNT(color_id)
  FROM products 
 WHERE item_id=1234 
 GROUP BY item_id

退货

color_id count
1, 323
2, 122
3, 554

我正在寻找具有最多实例的 color_id 3。

有没有一种快速简便的方法可以在没有 2 个查询的情况下获得我想要的东西?

4

4 回答 4

19
SELECT color_id AS id, COUNT(color_id) AS count 
FROM products 
WHERE item_id = 1234 AND color_id IS NOT NULL 
GROUP BY color_id 
ORDER BY count DESC
LIMIT 1;

这将为您提供 color_id 和该 color_id 的计数,按从最大到最小的计数排序。我想这就是你想要的。


为您的编辑...

SELECT color_id, COUNT(*) FROM products WHERE color_id = 3;
于 2013-01-10T02:03:26.397 回答
9
SELECT color_id
FROM
    (
        SELECT  color_id, COUNT(color_id) totalCount
        FROM    products 
        WHERE   item_id = 1234 
        GROUP   BY color_id 
    ) s
HAVING totalCount = MAX(totalCount)

更新 1

SELECT  color_id, COUNT(color_id) totalCount
FROM    products 
WHERE   item_id = 1234 
GROUP   BY color_id 
HAVING  COUNT(color_id) =
(
  SELECT  COUNT(color_id) totalCount
  FROM    products 
  WHERE   item_id = 1234 
  GROUP   BY color_id 
  ORDER BY totalCount DESC
  LIMIT 1  
)
于 2013-01-10T02:05:18.880 回答
3
SELECT 
  color_id, 
  COUNT(color_id) AS occurances
FROM so_test
GROUP BY color_id
ORDER BY occurances DESC
LIMIT 0, 1

这是一个带有基本表的示例小提琴,显示它的工作原理:sql fiddle

于 2013-01-10T02:13:16.757 回答
0

为简单起见,在 Oracle 中使用内置函数(仅适用于 Oracle 数据库 11g+ 版本):

select stats_mode(color_id) from so_test 

这将返回颜色 ID 的最高出现次数。

于 2020-11-13T13:52:59.220 回答