MySQL COUNT() across multiple columns

2020-04-16 04:49发布

问题:

I have been banging my head over this one for quite a while now but can not seem to get it working :(

I have a table which among other standard fields, also has a few fields for different values of a same kind (INT for example). Value of each field is unique -> meaning if it appears in a val_1 it will not appear in val_2 and val_n. It can be however repeated in next row. My table looks something like this:

| id | val_1 | val_2 | val_3 | ... | val_n | some other stuff | ... |

My question is: How can I count occurrences of certain values in my table? For example: I would like to know which value occurs the most.

回答1:

SELECT
  COUNT(DISTINCT val_1) AS val_1_count,
  COUNT(DISTINCT val_2) AS val_2_count,
  ...
FROM ...

will give you the counts for each field.

SELECT val_1, count(*) as val_1_count
FROM ...
GROUP BY val_1

will give you the counts for a value. You can use UNION to repeat this for val_1 to val_n in a single (kludgy) query.

If you want the counts over all fields, you need

SELECT val,count(*) as valcount
FROM (
  SELECT val_1 AS val FROM ...
  UNION ALL
  SELECT val_2 AS val FROM ...
  ...
) AS baseview
GROUP BY val


标签: mysql count