MYSQL从逗号分隔中选择不同值的计数

时间:2016-11-15 16:06:58

标签: mysql

如何从MySql中以逗号分隔值存储的数据中选择不同的值和相对计数?

表格中的数据如下所示:

"Category"    "Values"    
"red"         "D,A,D,D"    
"yellow"      "A,A,D,D"

欲望输出:

"red"    "D" "3"    
"red"    "A" "1"    
"yellow" "D" "2"    
"yellow" "A" "2"

你能想到在mysql中获得输出的好方法,就像我做的那样吗? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

使用派生表,您可以将字符串拆分为行

SELECT `Category`, SUBSTRING_INDEX(SUBSTRING_INDEX(t.`Values`, ',', n.n), ',', -1) `value`
FROM table1 t CROSS JOIN 
(
   SELECT a.N + b.N * 10 + 1 n
     FROM 
    (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
   ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
    ORDER BY n
) n
 WHERE n.n <= 1 + (LENGTH(t.`Values`) - LENGTH(REPLACE(t.`Values`, ',', '')))

然后只需GROUP BYCOUNT

<强> DEMO

SELECT `Category`, `value`, COUNT(*) as cnt
FROM (
    <previous query>
   ) T
GROUP BY  `Category`, `value`

enter image description here