开发者

MySQL distinct values across columns

开发者 https://www.devze.com 2023-04-09 05:21 出处:网络
I have the following table: idlbrblsrschbkot 110000100011000110001100011000110000 20100000100010100000

I have the following table:

id    lb     rb     ls     rs     ch     bk     ot
 1  10000  10001  10001  10001  10001  10001  10000
 2      0  10000      0  10001      0  10000      0
 3      0      0  10000  10001  10000      0      0
 4   开发者_开发问答   0      0      0  10000      0      0      0
 5      0      0      0  10000      0      0      0

I want to be able to get the total distinct values across all columns (excluding 0) so the result is as such:

Code   Qty
10000    8
10001    7

What's the easiest/best way to do this?

Thanks, Stu


You can do

SELECT col1, COUNT(*)
FROM
  (
  SELECT lb AS col1
  FROM table
    UNION ALL 
  SELECT rb
  FROM table
    UNION ALL ... etc
  ) a
WHERE col1 != 0
GROUP BY col1

Instead of WHERE col1 != 0 you can add WHERE field_name !=0 to each SELECT in UNION


SELECT code     AS Code
     , SUM(cnt) AS Qty
FROM
  (   SELECT lb AS code
           , COUNT(*) AS cnt
      FROM TableX
      GROUP BY lb        
  UNION ALL
      SELECT rb AS code
           , COUNT(*) AS cnt
      FROM TableX
      GROUP BY rb
  UNION ALL        
    ...
  UNION ALL
      SELECT ot AS code
           , COUNT(*) AS cnt
      FROM TableX
      GROUP BY ot
  ) AS tmp
GROUP BY code
0

精彩评论

暂无评论...
验证码 换一张
取 消