2017-08-17 93 views
1

新手需要一點幫助。有人可以提供一個查詢,以方便地讀,然後按月記錄匹配的兩個條件製表避免使用笨拙的重複這樣的代碼......按月計分匹配記錄

SELECT 
SUM(CASE 
    WHEN extract(YEAR FROM `date`) = "2017" 
    AND extract(MONTH FROM `date`) = "07" 
    AND `conditionA` = "A" 
    AND `conditionB` = "B" 
    THEN 1 else 0 END) 
AS 2017_07 

SUM(CASE 
    WHEN extract(YEAR FROM `date`) = "2017" 
    AND extract(MONTH FROM `date`) = "08" 
    AND `conditionA` = "A" 
    AND `conditionB` = "B" 
    THEN 1 else 0 END) 
AS 2017_08 

SUM(CASE 
    WHEN extract(YEAR FROM `date`) = "2017" 
    AND extract(MONTH FROM `date`) = "09" 
    AND `conditionA` = "A" 
    AND `conditionB` = "B" 
    THEN 1 else 0 END) 
AS 2017_09 

FROM `datatable` 
+0

請查看此鏈接(https://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/)以瞭解有關如何改進的更多信息該問題,並不張貼圖像 – TheGameiswar

+0

謝謝。我只是想提出更好的問題,但需要澄清一下,我應該做些什麼改變。我的問題似乎很簡潔,我發佈了一個格式化的查詢。我立即收到了問題的確切解決方案,儘管基本如此。你是否建議我應該發佈表格數據來實現這個簡單的事情? – Livefish

+0

如果你可以看看我發佈的鏈接,它可以幫助你..你沒有發佈任何表數據,預期結果,當前結果 – TheGameiswar

回答

3

數據放入行,不列:

SELECT extract(YEAR FROM `date`) as yyyy, extract(MONTH FROM `date`) as mm, 
     COUNT(*) 
FROM datatable 
WHERE `conditionA` = 'A' AND `conditionB` = 'B' 
GROUP BY extract(YEAR FROM `date`), extract(MONTH FROM `date`) 
ORDER BY yyyy, mm ; 
+0

完美。謝謝! – Livefish