我可以使用数据透视表在 Excel 中执行此操作,但我想找出一种直接从单个 SQL 查询执行此操作的方法。假设我有一份水果及其新鲜度 list :
**Fruit Freshness**
Banana New
Banana Ripe
Apple Ripe
Orange Old
Cherry New
Orange Ripe
Apple Old
Banana Old
Apple New
Apple New
Orange Ripe
Banana Old
Orange New
Cherry New
Cherry Ripe
我想计算“新鲜度”出现的次数,然后将它们排名为最频繁、第二频繁,依此类推。结果看起来像这样:
**Fruit Most common 2nd most common 3rd most common**
Banana New Old Ripe
Apple Old New Ripe
Orange Ripe New Old
Cherry New Ripe NA
这可以在一个查询中实现吗?
最佳答案
您可以使用 GROUP_CONCAT()聚合函数:
SELECT
Fruit, GROUP_CONCAT(Freshness ORDER BY cnt DESC) as Common
FROM (
SELECT Fruit, Freshness, COUNT(*) cnt
FROM
fruits
GROUP BY
Fruit, Freshness
) s
将返回如下值:
Fruit | Common
---------------------
Banana | New,Old,Ripe
Cherry | New,Ripe
... | ...
但是如果你想将结果分成三列,你可以结合前面的查询并使用 SUBSTRING_INDEX()从逗号分隔值中提取第一个、第二个和第三个值:
SELECT
Fruit,
SUBSTRING_INDEX(Common, ',', 1) AS most,
CASE WHEN CommonLIKE '%,%'
THEN SUBSTRING_INDEX(SUBSTRING_INDEX(Common, ',', 2), ',', -1) END AS second_most,
CASE WHEN CommonLIKE '%,%,%'
THEN SUBSTRING_INDEX(SUBSTRING_INDEX(Common, ',', 3), ',', -1) END AS third_most
FROM (
SELECT
Fruit, GROUP_CONCAT(Freshness ORDER BY cnt DESC) as Common
FROM (
SELECT Fruit, Freshness, COUNT(*) cnt
FROM
fruits
GROUP BY
Fruit, Freshness
) s
GROUP BY
Fruit
) s
关于mysql - SQL 查询返回最常见、第二常见、第三常见的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27028533/