我需要一个sql查询来合并我在不同列上的表上的所有数字,并找到它们出现的总和。
我的表结构是这样的
id | Pick1 | Pick2 | Pick3 | Pick4 | Pick5 | Pick6 |
----------------------------------------------------
1 | 1 | 23 | 56 | 56 | 78 | 89 |
----------------------------------------------------
2 | 9 | 49 | 90 | 56 | 78 | 89 |
----------------------------------------------------
3 | 2 | 65 | 56 | 56 | 78 | 89 |
----------------------------------------------------
4 | 1 | 23 | 23 | 56 | 78 | 89 |
预期结果
Number | Frequency
-------------------
23 | 5
-------------------
56 | 7
-------------------
89 | 4
....
有人可以帮忙吗?
答案 0 :(得分:0)
您需要在子查询中使用UNION ALL
合并所有记录。试试这个,
SELECT x.a `Number`,
COUNT(x.a) `Frequency`
FROM
(
SELECT Pick1 a
FROM TableNAME
UNION ALL
SELECT Pick2 a
FROM TableNAME
UNION ALL
SELECT Pick3 a
FROM TableNAME
UNION ALL
SELECT Pick4 a
FROM TableNAME
UNION ALL
SELECT Pick5 a
FROM TableNAME
UNION ALL
SELECT Pick6 a
FROM TableNAME
) x
GROUP BY x.a
答案 1 :(得分:0)
SELECT pick AS `Number`,
COUNT(1) AS Frequency
FROM(
SELECT Pick1 AS pick
FROM table_name
UNION ALL
SELECT Pick2 AS pick
FROM table_name
SELECT Pick3 AS pick
FROM table_name
SELECT Pick4 AS pick
FROM table_name
SELECT Pick5 AS pick
FROM table_name
SELECT Pick6 AS pick
FROM table_name
) a
GROUP BY a.pick;
答案 2 :(得分:0)
如果您可以将表格重新组织成如下所示的结构,那将会更容易:
id | pick | nr
------------------
1 1 1
1 2 23
1 3 56
在这样的表格中,您可以轻松地对数字进行分组和计数。 您的项目是否可以像这样更改表结构?
或者,如果不可能,您可以创建一个帮助视图来排列此结构中的数据,然后将此结果用于进一步处理。可以使用六个选择语句的UNION来构造这样的视图。如果您需要进一步的帮助,请告诉我。