0

如何获得连续数字的计数。

例子

数据库

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
4

3 回答 3

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

于 2013-09-18T20:27:38.240 回答
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);
于 2013-09-18T20:23:38.307 回答
0

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

所以例如你$array would be array(10,20,30,40,40,50,60,70)的前两行。然后使用print_r(array_count_values($array));

数组计数值

于 2013-09-18T20:14:51.390 回答