SQL计数多个列和行的特定值

时间:2016-05-16 18:33:24

标签: mysql sql

我觉得这应该很容易,但似乎无法找到解决方案。 假设我有下表:

|--------||---||---||---||---||---||---||---|
|Company ||q1 ||q2 ||q3 ||q4 ||q5 ||q6 ||q7 |
|--------||---||---||---||---||---||---||---|
|abc     ||1  ||2  ||1  ||3  ||2  ||2  ||1  |
|abc     ||2  ||2  ||1  ||2  ||3  ||1  ||1  |
|abc     ||1  ||1  ||3  ||3  ||1  ||2  ||2  |
|abc     ||1  ||2  ||1  ||3  ||0  ||1  ||3  |

我想算一下次数' 1'出现在表格中,因此在这种情况下,查询应该以12结果。我尝试了“硬编码”#39;它,像下面的查询。但这只会导致行包含1,所以在这种情况下4.我如何计算次数' 1'发生,从而导致12?

的计数
SELECT COUNT(*) 
FROM table
WHERE Company = 'abc'
AND (
q1 =  '1'
OR q2 =  '1'
OR q3 =  '1'
OR q4 =  '1'
OR q5 =  '1'
OR q6 =  '1'
OR q7 =  '1'
)

5 个答案:

答案 0 :(得分:5)

SELECT SUM(
    IF(q1 = 1, 1, 0) +
    IF(q2 = 1, 1, 0) +
    IF(q3 = 1, 1, 0) +
    IF(q4 = 1, 1, 0) +
    IF(q5 = 1, 1, 0) +
    IF(q6 = 1, 1, 0) +
    IF(q7 = 1, 1, 0)
)
FROM table
WHERE Company = 'abc'

答案 1 :(得分:4)

这是非常奇怪的任务,但是:

http://sqlfiddle.com/#!9/2e7aa/3

SELECT SUM((q1='1')+(q2='1')+(q3='1')+(q4='1')+(q5='1')+(q6='1')+(q7='1')) 
FROM table
WHERE Company = 'abc'
AND '1' IN (q1,q2,q3,q4,q5,q6,q7)

答案 2 :(得分:3)

不太容易,每列需要硬编码。我会尝试使用CASEDECODE

SELECT 
SUM(
CASE WHEN q1 = 1 THEN 1 ELSE 0 END +
CASE WHEN q2 = 1 THEN 1 ELSE 0 END +
CASE WHEN q3 = 1 THEN 1 ELSE 0 END +
CASE WHEN q4 = 1 THEN 1 ELSE 0 END +
CASE WHEN q5 = 1 THEN 1 ELSE 0 END +
CASE WHEN q6 = 1 THEN 1 ELSE 0 END +
CASE WHEN q7 = 1 THEN 1 ELSE 0 END)
FROM table
WHERE Company = 'abc'

使用SUM代替COUNT将允许CASE语句为SUM

答案 3 :(得分:3)

使用条件COUNT

SELECT COUNT(case when q1 = '1' then 1 end)  + 
       COUNT(case when q2 = '1' then 1 end)  + 
       COUNT(case when q3 = '1' then 1 end)  + 
       COUNT(case when q4 = '1' then 1 end)  + 
       COUNT(case when q5 = '1' then 1 end)  + 
       COUNT(case when q6 = '1' then 1 end)  + 
       COUNT(case when q7 = '1' then 1 end) as ones_total
FROM table
WHERE Company = 'abc'

答案 4 :(得分:2)

出于效率原因,我不建议实际使用这种方法;但是出于学习目的,这是另一种方法,你可以根据你的思维方式解决问题。

select sum(c) as total_ones
from
    (
    select count(*) c from table where q1 = 1 union all
    select count(*)   from table where q2 = 1 union all
    select count(*)   from table where q3 = 1 union all
    select count(*)   from table where q4 = 1 union all
    select count(*)   from table where q5 = 1 union all
    select count(*)   from table where q6 = 1 union all
    select count(*)   from table where q7 = 1
    ) t