MySQL COUNT() across multiple columns

前端 未结 1 603
野性不改
野性不改 2021-01-22 17:40

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 fi

相关标签:
1条回答
  • 2021-01-22 18:16
    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
    
    0 讨论(0)
提交回复
热议问题