如何在MYSQL中获取摘要计数

时间:2013-09-18 20:08:51

标签: php mysql database summary

如何获取连续数字的数量。

实施例

mydtabase

num1 num2 num3 num4
 10   20   30   40
 40   50   60   70
 20   10   90   80
 01   60   81   99

所以我希望结果适用于整个表格:

01 1
10 2
20 2
30 1

依此类推,如果我只想要前两行的摘要,我会得到:

10 1
20 1
30 1
40 2
50 1
60 1
70 1

3 个答案:

答案 0 :(得分:2)

要获得整个表的结果,您可以使用如下查询:

SELECT num, COUNT(*) cnt
FROM (
  SELECT num1 AS num FROM tableName
  UNION ALL 
  SELECT num2 AS num FROM tableName
  UNION ALL 
  SELECT num3 AS num FROM tableName
  UNION ALL 
  SELECT num4 AS num FROM tableName
) s
GROUP BY num

要仅获取前两行的结果,可以使用LIMIT:

SELECT num, COUNT(*) cnt
FROM (
  SELECT id, num1 AS num FROM tableName
  UNION ALL 
  SELECT id, num2 AS num FROM tableName
  UNION ALL 
  SELECT id, num3 AS num FROM tableName
  UNION ALL 
  SELECT id, num4 AS num FROM tableName
  ORDER BY id
  LIMIT 8
) s
GROUP BY num

其中8是4列*您想要的行数2,但您需要使用ORDER BY子句。一个例子是here

答案 1 :(得分:1)

你的问题的答案是,你会忽略表格,然后聚合:

  select (case when n.n = 1 then num1
               when n.n = 2 then num2
               when n.n = 3 then num3
               when n.n = 4 then num4
          end) as num, count(*)
  from t cross join
       (select 1 as n union all select 2 union all select 3 union all select 4) n
  group by (case when n.n = 1 then num1
                 when n.n = 2 then num2
                 when n.n = 3 then num3
                 when n.n = 4 then num4
            end);

答案 2 :(得分:0)

如果要用PHP完成(我假设是这样),将每个元素放入一个数组中。

例如,您的$array would be array(10,20,30,40,40,50,60,70)代表前2行。 然后使用print_r(array_count_values($array));

array-count-values