我有一个表suivis
,其中包含id_action和id_individu列,该表可以包含多个重复值(不是整个行,只有该列)。
我还有一个表individus
,其中包含一列statut_collaborateur
,该表可以具有两个值:'no'和'granted'。
我需要帮助来计算statut_collaborateur =否和statut_collaborateur =授予但仅一次的id_individu的数量。
现在,我设法做到了:
SELECT j.date_debut, j.date_fin, j.titre, so.id_identite, so.nom_societe,
SUM(CASE WHEN (i.statut_collaborateur = 'granted') THEN 1 ELSE 0 END) AS interne,
SUM(CASE WHEN (i.statut_collaborateur = 'no') THEN 1 ELSE 0 END) AS externe,
r.nom_responsable
FROM individus AS i
LEFT JOIN suivis AS s ON s.id_individu = i.id_individu
LEFT JOIN jurys AS j ON j.id_jury = s.id_jury
LEFT JOIN societes AS so ON so.id_societe = j.id_societe
LEFT JOIN responsables AS r ON r.id_responsable = j.id_responsable
WHERE s.id_action = 22
AND j.statut IN (1,3)
AND j.date_debut BETWEEN '2018-01-01 00:00:00' AND '2018-10-23 23:59:59'
GROUP BY s.id_jury`
主要问题是我必须总和,我也尝试过计数,但结果相同,我的计数是5,应该是3(3个独立的individu)。
答案 0 :(得分:0)
选择的列数应包含在分组依据
SELECT j.date_debut, j.date_fin, j.titre, so.id_identite, so.nom_societe,
SUM(CASE WHEN (i.statut_collaborateur = 'granted') THEN 1 ELSE 0 END) AS interne,
SUM(CASE WHEN (i.statut_collaborateur = 'no') THEN 1 ELSE 0 END) AS externe,
r.nom_responsable
FROM individus AS i
LEFT JOIN suivis AS s ON s.id_individu = i.id_individu
LEFT JOIN jurys AS j ON j.id_jury = s.id_jury
LEFT JOIN societes AS so ON so.id_societe = j.id_societe
LEFT JOIN responsables AS r ON r.id_responsable = j.id_responsable
WHERE s.id_action = 22
AND j.statut IN (1,3)
AND j.date_debut BETWEEN '2018-01-01 00:00:00' AND '2018-10-23 23:59:59'
GROUP BY j.date_debut, j.date_fin, j.titre, so.id_identite, so.nom_societe,r.nom_responsable
答案 1 :(得分:0)
仅使用表individus的不同语句加入所需的列
SELECT j.date_debut, j.date_fin, j.titre, so.id_identite, so.nom_societe,
SUM(CASE WHEN (i.statut_collaborateur = 'granted') THEN 1 ELSE 0 END) AS interne,
SUM(CASE WHEN (i.statut_collaborateur = 'no') THEN 1 ELSE 0 END) AS externe,
r.nom_responsable
FROM (SELECT DISTINCT i.id_individu ,i.statut_collaborateur from individus )AS i
LEFT JOIN suivis AS s ON s.id_individu = i.id_individu
LEFT JOIN jurys AS j ON j.id_jury = s.id_jury
LEFT JOIN societes AS so ON so.id_societe = j.id_societe
LEFT JOIN responsables AS r ON r.id_responsable = j.id_responsable
WHERE s.id_action = 22
AND j.statut IN (1,3)
AND j.date_debut BETWEEN '2018-01-01 00:00:00' AND '2018-10-23 23:59:59'
GROUP BY j.date_debut, j.date_fin, j.titre, so.id_identite, so.nom_societe,r.nom_responsable