MySQL distinct values across columns
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
精彩评论