SELECT qurum_id, qurum, COUNT(qurum1) AS I FROM `qurum` AS qur
JOIN (SELECT id, qurum1,input_date FROM DATA ) `aa` ON qur.qurum_id =
aa.qurum1
WHERE DATE_FORMAT(aa.input_date, '%Y') = $year AND DATE_FORMAT(aa.input_date, '%m') < 07
GROUP BY qurum_id
ORDER BY qurum_id
和
SELECT qurum_id, qurum, COUNT(qurum1) AS II FROM `qurum` AS qur2
JOIN (SELECT id, qurum1,input_date FROM DATA ) `bb` ON qur2.qurum_id =
bb.qurum1
WHERE DATE_FORMAT(bb.input_date, '%Y') = $year AND DATE_FORMAT(bb.input_date, '%m') BETWEEN 06 AND 12
GROUP BY qurum_id
ORDER BY qurum_id
如何将这些查询加入1?我需要这样的列 - qurum_id,qurum,I,II。
答案 0 :(得分:1)
您可以使用条件聚合。诀窍是根据月份条件采取条件计数记录,这对于您当前的两个查询是不同的。请注意,该年份的WHERE
条件是不相关的,因为两个查询都共享此条件。
SELECT
qurum_id,
SUM(CASE WHEN DATE_FORMAT(aa.input_date, '%m') < 07
THEN 1 END) AS I,
SUM(CASE WHEN DATE_FORMAT(aa.input_date, '%m') BETWEEN 06 AND 12
THEN 1 END) AS II
FROM qurum AS qur
INNER JOIN (SELECT id, qurum1,input_date FROM DATA ) AS aa
ON qur.qurum_id = aa.qurum1
WHERE DATE_FORMAT(aa.input_date, '%Y') = $year
GROUP BY qurum_id
ORDER BY qurum_id