2

我需要一个 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
....

任何人都可以帮忙吗?

4

3 回答 3

0

如果您可以将表格重新组织成如下结构,那就容易多了:

id | pick | nr
------------------
1    1       1  
1    2      23
1    3      56

在这样的表格中,您可以轻松地对数字进行分组和计数。在您的项目中是否可以像这样更改表结构?

或者,如果不可能,您可以创建一个帮助视图,在此结构中排列数据,然后将此结果用于进一步处理。这样的视图可以通过使用六个 select 语句的 UNION 来构建。如果您在这方面需要进一步的帮助,请告诉我。

于 2012-09-11T09:19:43.170 回答
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
于 2012-09-11T09:12:44.340 回答
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;
于 2012-09-11T09:13:42.473 回答