sql查詢每個季度的資料並自動補零
阿新 • • 發佈:2019-01-02
對錶中每個季度的資料進行統計並實現自動補零,首先先查詢出表中每個季度的資料
SELECT QUARTER(applicationdate) as mon, COUNT(*) as con FROM qm_technical_zero GROUP BY QUARTER(applicationdate)
從表qm_technical_zero中按季度查詢日期applicationdate的資料,但是隻能出現前三季度的資料,第四季度為零所以不顯示。
結果如下所示
然後在建立一個表
SELECT 1 as click_date UNION ALL SELECT 2 as click_date UNION ALL SELECT 3 as click_date UNION ALL SELECT 4 as click_date
結果如下圖所示
然後對兩個表進行聯合查詢就可以實現補零操作。
SELECT click_date as q,IFNULL(b.con,0) as c FROM(SELECT 1 as click_date UNION ALL SELECT 2 as click_date UNION ALL SELECT 3 as click_date UNION ALL SELECT 4 as click_date) a LEFT JOIN( SELECT QUARTER(applicationdate) as mon, COUNT(*) as con FROM qm_technical_zero GROUP BY QUARTER(applicationdate)) b ON click_date=b.mon
進行聯合查詢後結果如下所示: