我有一张表格,其数据类似于下表
id c1 c2
1 a b
2 e f
3 b d
4 x e
我希望得到两列上的distint值及其总和。我的预期输出是
a 1
b 2
d 1
e 2
f 1
x 1
第一列是整体不同的值,第二列是出现的时间。如何在MYSQL
中获取它?
答案 0 :(得分:1)
正如jarlh在评论中所说,您可以使用UNION ALL
子查询执行此操作:
SELECT col, COUNT(*)
FROM
(
SELECT c1 AS col FROM thetable
UNION ALL
SELECT c2 AS col FROM thetable
) T
GROUP BY col
答案 1 :(得分:0)
您可以通过创建临时表来执行此操作:
从你的例子:
select * from Table1;
+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
| 1 | a | b |
| 2 | e | f |
| 3 | b | d |
| 4 | x | e |
+------+------+------+
创建临时表:
create temporary table dummy (col1 text);
从表中插入TEMP表值:
insert into dummy select col2 from Table1;
insert into dummy select col3 from Table1;
现在TEMP表:
select * from dummy;
+------+
| col1 |
+------+
| a |
| e |
| b |
| x |
| b |
| f |
| d |
| e |
+------+
现在您的预期结果:
select distinct col1 , count(*) from dummy group by col1;
+------+----------+
| col1 | count(*) |
+------+----------+
| a | 1 |
| b | 2 |
| d | 1 |
| e | 2 |
| f | 1 |
| x | 1 |
+------+----------+