[英]Return PAIR of all unique possible combinations from single column in SQL
[英]Return all possible combinations of values within a single column in MySQL
我正在使用 MySQL。 如何从单个列返回所有可能的组合并计算对应列的总数。 例如:
name | grade
-------------------
john | A
any | B
cindy | C
kim | C
将返回如下内容:
mark | count
-------------------
A | 1
B | 1
C | 2
AB | 2
AC | 3
BC | 3
ABC | 4
我一直在寻找解决方案,最接近的解决方案是在 SQL 的单个列中返回所有可能的值组合。 但在仅生成组合和 ORACLE 中。
这是我为这个问题创建的数据集:
CREATE TABLE users
(`name` varchar(5), `grade` varchar(1))
;
INSERT INTO users
(`name`, `grade`)
VALUES
('john', 'A'),
('any', 'B'),
('cindy', 'C'),
('kim', 'C')
;
...和 SQL 小提琴相同:
您可以使用递归公用表表达式:
with recursive cte (n) AS
(
select distinct cast(u.grade as char(255)) from users u
union all
select concat(u.grade, c.n)
from users u
join cte c on u.grade != c.n
where position(u.grade in c.n)=0
and u.grade < c.n
)
select c.n, count(*)
from cte c
join users u on position(u.grade in c.n)
group by c.n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.