2017-04-17 52 views
0
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 

2查詢1使用2個不同的WHERE

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

你可以用'union' – Shadow

+0

同時存儲腳本在兩個不同溫度的/ var表的輸出,然後用結合。 –

+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 
+1

非常感謝! –

相關問題