2017-02-17 58 views
0

我有一個支付表按天分組MySQL的選擇默認值,如果沒有結果

select 
day(created), 
sum(payments.amount) 
from payments 
group by day(created) 

輸出

day | amount 
1 | 432 
2 | 4567 
5 | 345 
6 | 2345 
7 | 97 

這是很好的,但我想,以放入一些0沒有付款的日子。

預期輸出:

day | amount 
1 | 432 
2 | 4567 
3 | 0 
4 | 0 
5 | 345 
6 | 2345 
7 | 97 
+0

可能重複[Mysql group by weekday,填寫缺少的工作日](http://stackoverflow.com/questions/40403859/mysql-group-by-weekday-fill-在失蹤的工作日) –

+0

檢查這個答案:http://stackoverflow.com/a/8888404/1040225 –

回答

0

因爲你沒有在payments表中的所有的約會,你可以這樣做:

select 
    d, 
    ifnull(sum(p.amount),0) sum_amount 
from (
     select 1 as d 
     union all 
     select 2 
     union all 
     select 3 
     union all 
     select 4 
     union all 
     select 5 
     union all 
     select 6 
     union all 
     select 7 
    ) d 
    left join payments p 
    on day(p.created) = d.d 
group by d 
order by d 

樣品在這裏:http://sqlfiddle.com/#!9/cb09d1/2

+0

不,我沒有在支付表中的所有日期,但我需要返回他們,就好像他們一樣如果他們是空的 –

+0

@BlairAnderson:根據你的評論請看ed回答。 – bernie

0

您可能沒有在表中某些日期的數據,因此你不能要求引擎回報你。 簡直不能,它基本上對人類的日曆一無所知:-)

所以,你必須爲這些天追溯地生成零記錄的存根記錄,或者使用@bernie建議的方法,這種特殊的方式或物化在永久表中持有天數從1到31.

相關問題