我正在尝试通过2列查询压缩订单,按1列查询订单和细分列。如果这有一个正确的名称,我将非常感谢它知道它是什么!
示例:
ocean
name | type | colour
fishy | salmon | red
splishy | salmon | red
splashy | salmon | pink
sploshy | salmon | pink
floaty | whale | blue
humprhey | whale | grey
wilson | whale | grey
寻找(我不确定这是做什么的):
type | count | colour breakdown
salmon| 4 | 2 red, 2 pink
whale | 3 | 1 blue, 2 grey
优先使用最少的字符串函数。
不确定如何继续:
(按一栏排序)
SELECT o.type, count(*)
FROM ocean o
GROUP BY `type`
type | count
salmon| 4
whale | 3
(按两栏排序)
SELECT o.type, o.colour, count(*)
FROM ocean o
GROUP BY `type`, `colour`
type | colour | count
salmon| red | 2
salmon| pink | 2
whale | blue | 1
whale | grey | 2
答案 0 :(得分:2)
丑陋,未经测试,但可能只是做你想要的:
SELECT type, SUM(color_count),
GROUP_CONCAT(CONCAT(color_count, ' ', colour) SEPARATOR ', ') AS colour_breakdown
FROM (
SELECT type, colour, COUNT(colour) AS colour_count
FROM ocean
GROUP BY type, colour
) AS subt
GROUP BY type
答案 1 :(得分:1)
使用第二个查询作为数据源,您可以使用group_concat()
获取所需的输出:
select type, sum(`count`), group_concat(colBreak separator ',') as color_breakdown
from
(
SELECT
o.type,
o.colour,
count(o.type) as `count`,
concat(o.colour, ' ', count(o.type)) as colBreak
FROM ocean o
GROUP BY `type`, `colour`
) as a
group by type;