SQL通过选择加入几个count(*)组

时间:2009-01-24 13:25:50

标签: sql

我有下表包含6/49彩票的中奖号码。

+-----+------------+----+----+----+----+----+----+-------+
|  id | draw       | n1 | n2 | n3 | n4 | n5 | n6 | bonus |
+-----+------------+----+----+----+----+----+----+-------+
|   1 | 1982-06-12 |  3 | 11 | 12 | 14 | 41 | 43 |    13 |
|   2 | 1982-06-19 |  8 | 33 | 36 | 37 | 39 | 41 |     9 |
|   3 | 1982-06-26 |  1 |  6 | 23 | 24 | 27 | 39 |    34 |
|   4 | 1982-07-03 |  3 |  9 | 10 | 13 | 20 | 43 |    34 |
|   5 | 1982-07-10 |  5 | 14 | 21 | 31 | 34 | 47 |    45 |
|   6 | 1982-07-17 |  8 | 20 | 21 | 25 | 31 | 41 |    33 |
|   7 | 1982-07-24 | 18 | 25 | 28 | 33 | 36 | 42 |     7 |
|   8 | 1982-07-31 |  7 | 16 | 17 | 31 | 40 | 48 |    26 |
|   9 | 1982-08-07 |  5 | 10 | 23 | 27 | 37 | 38 |    33 |
|  10 | 1982-08-14 |  4 | 15 | 30 | 37 | 46 | 48 |     3 |
+-----+------------+----+----+----+----+----+----+-------+

我想创建一个频率图表来查看n1,n2,...,n6列中数字的出现。

SELECT n1, COUNT(n1) as freq1 FROM lottery GROUP BY n1;
SELECT n2, COUNT(n2) as freq2 FROM lottery GROUP BY n2;
SELECT n3, COUNT(n3) as freq3 FROM lottery GROUP BY n3;
SELECT n4, COUNT(n4) as freq4 FROM lottery GROUP BY n4;
SELECT n5, COUNT(n5) as freq5 FROM lottery GROUP BY n5;
SELECT n6, COUNT(n6) as freq6 FROM lottery GROUP BY n6;

基本上我正在尝试将上述查询合并到一个查询中。

提前致谢。

4 个答案:

答案 0 :(得分:8)

根据您的表格布局,您不能通过任何其他方式将查询组合成单个查询,而不是将您的查询联合起来,或者将基表联合到转置版本中:

SELECT n, COUNT(*) as freq FROM 
(
  SELECT n1 AS n FROM lottery
  UNION ALL
  SELECT n2 FROM lottery
  UNION ALL
  SELECT n3 FROM lottery
  UNION ALL
  SELECT n4 FROM lottery
  UNION ALL
  SELECT n5 FROM lottery
  UNION ALL
  SELECT n6 FROM lottery
) as transposed
GROUP BY n
ORDER BY COUNT(*) DESC

答案 1 :(得分:1)

我会做一些非常相似的事情,但尝试减少子查询返回的记录数...

SELECT
    n                     AS [n],
    SUM([data].count_n)   AS [count_n]
FROM
    (
        SELECT n1 AS [n], COUNT(*) AS [count_n] FROM lottery GROUP BY n1
        UNION ALL
        SELECT n2 AS [n], COUNT(*) AS [count_n] FROM lottery GROUP BY n2
        UNION ALL
        SELECT n3 AS [n], COUNT(*) AS [count_n] FROM lottery GROUP BY n3
        UNION ALL
        SELECT n4 AS [n], COUNT(*) AS [count_n] FROM lottery GROUP BY n4
        UNION ALL
        SELECT n5 AS [n], COUNT(*) AS [count_n] FROM lottery GROUP BY n5
        UNION ALL
        SELECT n6 AS [n], COUNT(*) AS [count_n] FROM lottery GROUP BY n6
    )
    as [data]
GROUP BY
    [data].n
ORDER BY
    SUM([data].count_n) DESC

答案 2 :(得分:0)

建立联盟: 从彩票中选择n1 工会从彩票中选择n2 .... 然后制作你的汇总!

答案 3 :(得分:0)

tomalak,我认为你的版本不会返回正确的结果集。 编辑:你改了它,现在它是正确的。 :)

SELECT COUNT(*), n1 FROM
(
SELECT n1 FROM tbl1
UNION ALL SELECT n2 FROM tbl1
UNION ALL SELECT n3 FROM tbl1
) AS nicetbl
GROUP BY n1