跨列的MySQL不同值

时间:2011-09-28 13:47:35

标签: mysql distinct multiple-columns

我有下表:

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

我希望能够获得所有列的总不同值(不包括0),因此结果是这样的:

Code   Qty
10000    8
10001    7

最简单/最好的方法是什么?

谢谢,Stu

2 个答案:

答案 0 :(得分:1)

你可以做到

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

您可以向WHERE col1 != 0

中的每个WHERE field_name !=0添加SELECT,而不是UNION

答案 1 :(得分:0)

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