我在mysql中有一个表,其值为给定值
+--------+---+---+---+---+----+
+ emp_no + A + B + C + D + E +
+--------+---+---+---+---+----+
+ 100 + 1 + 0 + 2 + 1 + 1 +
+ 101 + 2 + 1 + 1 + 3 + 1 +
+ 102 + 3 + 4 + 4 + 2 + 5 +
+ 103 + 5 + 3 + 4 + 1 + 2 +
+--------+---+---+---+---+----+
我是否可以编写一个sql查询,它将从上述表中获取总计数为1,总计数为2,总计数为3 ....对此非常感谢。
谢谢
答案 0 :(得分:3)
试试这个:
SELECT num, SUM(counts) FROM (
SELECT A num, COUNT(A) counts FROM table1 GROUP BY A
union all
SELECT B num, COUNT(B) counts FROM table1 GROUP BY B
union all
SELECT C num, COUNT(C) counts FROM table1 GROUP BY C
union all
SELECT D num, COUNT(D) counts FROM table1 GROUP BY D
union all
SELECT E num, COUNT(E) counts FROM table1 GROUP BY E
) temp
GROUP BY num
答案 1 :(得分:0)
是的,但有点复杂。这是一种方法,通过取消隐藏值然后聚合:
select val, count(*)
from (select emp_no,
(case when n.n = 1 then A
when n.n = 2 then B
when n.n = 3 then C
when n.n = 4 then D
when n.n = 5 then E
end) as val
from table t cross join
(select 1 as n union all select 2 union all select 3 union all select 4 union all select 5
) n
) e;
答案 2 :(得分:0)
可能SUM()
具有布尔条件的总和。看看这个:
SELECT
SUM(
(`a` = 1)
+
(`b` = 1)
+
(`c` = 1)
+
(`d` = 1)
+
(`e` = 1)
) as `1`,
SUM(
(`a` = 2)
+
(`b` = 2)
+
(`c` = 2)
+
(`d` = 2)
+
(`e` = 2)
) as `2`,
SUM(
(`a` = 3)
+
(`b` = 3)
+
(`c` = 3)
+
(`d` = 3)
+
(`e` = 3)
) as `3`,
SUM(
(`a` = 4)
+
(`b` = 4)
+
(`c` = 4)
+
(`d` = 4)
+
(`e` = 4)
) as `4`,
SUM(
(`a` = 5)
+
(`b` = 5)
+
(`c` = 5)
+
(`d` = 5)
+
(`e` = 5)
) as `5`
FROM
`table`;