我有一个包含值的表(字段值):
CREATE TABLE values (
questionario_id INT(10) UNSIGNED NOT NULL,
insegnamento_id INT(11) NOT NULL,
domanda_id TINYINT(3) UNSIGNED NOT NULL,
valore TINYINT(3) UNSIGNED NOT NULL COMMENT '1,2,3,4',
...
我想计算具有值(valore)1的所有行以及具有值2,3和4的所有行.WHERE子句是常见的。
我可以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
...
我不喜欢这个,因为我必须重复整个连接和WHERE子句。
出于同样的原因,我不喜欢这种形式:
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,
...
尝试了CASE选项:
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
但它不起作用。 任何提示?
答案 0 :(得分:5)
group by
不会帮助你吗?
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
答案 1 :(得分:3)
对于透视版本
使用
SUM(CASE WHEN V.valore=1 THEN 1 ELSE 0 END)
或者
COUNT(CASE WHEN V.valore=1 THEN 1 END) /*ELSE NULL is implicit*/
不
COUNT(CASE WHEN V.valore=1 THEN 1 ELSE 0 END)
COUNT
计算所有非空值,1
和0
均为NOT NULL
,因此您的代码实际上只是重复COUNT(*)
三次。