计算列之间的不同值

时间:2018-06-16 21:39:16

标签: mysql

我有这样的数据:

-----------------------------------------------------
|id |  col1 |  col2 |  col3 |  col4 |  col5 |  col6 |
-----------------------------------------------------
| 1 |   12  |    0  |   10  |   12  |    0  |   11  |
| 2 |   12  |    0  |    0  |   10  |    0  |   11  |
| 3 |   12  |   14  |    0  |    0  |    0  |   11  |
| 4 |   12  |    0  |    0  |   11  |   14  |   11  |
| 5 |   12  |    0  |   14  |   10  |    0  |   11  |
| 6 |   12  |   10  |    0  |    0  |    0  |   11  |
-----------------------------------------------------

我需要返回6列中所有不同值的计数:

----------------
| Qty | myValue|
----------------
|  4  |   10   |
|  7  |   11   |
|  7  |   12   |
|  3  |   14   |
----------------

这可以在一个查询中使用吗?我可以在一个列上执行此操作:

SELECT count(*) AS Qty, col1 AS myValue FROM myTable GROUP BY col1

但不确定如何在该声明中包含其他5列

2 个答案:

答案 0 :(得分:1)

使用UNION ALL,您可以单独获取每列,并按最后的计数分组

SELECT myValue, COUNT(*) as total
FROM 
  (
    (SELECT col1 as myValue FROM a)
    UNION ALL
    (SELECT col2 as myValue FROM a)
    UNION ALL
    (SELECT col3 as myValue FROM a)
    UNION ALL
    (SELECT col4 as myValue FROM a)
    UNION ALL
    (SELECT col5 as myValue FROM a)
    UNION ALL
    (SELECT col6 as myValue FROM a)
  ) T
GROUP BY myValue
HAVING myValue > 0;

请参阅SQL fiiddle demo

答案 1 :(得分:0)

您可以使用union作为当前结构,但我猜您可能需要更好的数据结构

select col,count(*) as qty
from(
    select col1 as col from table
    union all
    select col2 as col from table
    union all
    select col3 as col from table
    union all
    select col4 as col from table
    union all
    select col5 as col from table
    union all
    select col6 as col from table
) t
group by col