开发者

SQL counting rows having different values

I have a table with values (field valore):

CREATE TABLE values (
    questionario_id INT(10) UNSIGNED NOT NULL,
    insegnamento_id INT(11) NOT NULL,
    d开发者_如何学JAVAomanda_id TINYINT(3) UNSIGNED NOT NULL,
    valore TINYINT(3) UNSIGNED NOT NULL COMMENT '1,2,3,4',
...

I want to count all the rows that have values (valore) 1 and all those having value 2, 3 and 4. The WHERE clause is common.

I could UNION:

SELECT
    COUNT(V.valore) AS valori_1
FROM
        values V
JOIN    questionari Q ON (V.questionario_id = Q.id) 
JOIN    sessioni S ON (Q.sessione_id = S.id)
WHERE   V.domanda_id = 1 AND S.anno_accademico = 0 AND S.settimana = 0
AND V.valore=1
UNION SELECT
    COUNT(V.valore) AS valori_2
FROM
        values V
JOIN    questionari Q ON (V.questionario_id = Q.id) 
JOIN    sessioni S ON (Q.sessione_id = S.id)
WHERE   V.domanda_id = 1 AND S.anno_accademico = 0 AND S.settimana = 0
AND V.valore=2
UNION
...

I don't like this because I have to repeat the whole joins and the WHERE clauses.

For the same reason I don't like this other form:

SELECT
    (SELECT COUNT(V.valore) FROM values V WHERE ...) AS C1,
    (SELECT COUNT(V.valore) FROM values V WHERE ...) AS C2,
    (SELECT COUNT(V.valore) FROM values V WHERE ...) AS C3,
    ...

Tried the CASE option:

 SELECT
        COUNT(CASE WHEN V.valore=1 THEN 1 ELSE 0 END) AS C1,
        COUNT(CASE WHEN V.valore=2 THEN 1 ELSE 0 END) AS C2,
        COUNT(CASE WHEN V.valore=3 THEN 1 ELSE 0 END) AS C3
    FROM
            values V
    JOIN    questionari Q ON (V.questionario_id = Q.id) 
    JOIN    sessioni S ON (Q.sessione_id = S.id)
    WHERE
        V.domanda_id = 1
    AND 
        S.anno_accademico = 0
    AND 
        S.settimana = 0

but it doesn't work. Any hints?


Wouldn't a group by help you?

SELECT V.valore, COUNT(V.valore) AS valori_1
FROM
        values V
JOIN    questionari Q ON (V.questionario_id = Q.id) 
JOIN    sessioni S ON (Q.sessione_id = S.id)
WHERE   V.domanda_id = 1 AND S.anno_accademico = 0 AND S.settimana = 0
GROUP BY V.valore


For the pivoted version

Use

SUM(CASE WHEN V.valore=1 THEN 1 ELSE 0 END)

Or

COUNT(CASE WHEN V.valore=1 THEN 1  END) /*ELSE NULL is implicit*/

Not

COUNT(CASE WHEN V.valore=1 THEN 1 ELSE 0 END)

COUNT counts all non null values and 1 and 0 are both NOT NULL so your code is effectively just repeating COUNT(*) three times.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜