Question

How do I get the count of numbers in a row.

Example

mydtabase

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

so I want the results to be for the entire table:

01 1
10 2
20 2
30 1

and so on such that if I want the summary for only the first 2 lines I would get:

10 1
20 1
30 1
40 2
50 1
60 1
70 1
Était-ce utile?

La solution

To get the result for the entire table you could use a query like this:

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

To get the results only for the first two rows, you could use 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

where 8 is 4 columns * the number of rows you want 2, but you need to use an ORDER BY clause. An example is here.

Autres conseils

The answer to your question is that you would unpivot the table and then aggregate:

  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);

If its to be done with PHP (which I assume is), put every element into an array.

so for example your $array would be array(10,20,30,40,40,50,60,70) for first 2 lines. And then use print_r(array_count_values($array));

array-count-values

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top