這裏的典型方法是首先編寫一個查詢,獲取您想要的日期列表,然後使用外部聯接將該事務處理範圍內的日期的交易金額關聯起來。
我的建議是安裝common_schema並使用common_schema.numbers表生成日期列表。
例如,你可以這樣運行了一個查詢來獲取過去30天(不包括今天):
select (current_date() - interval n day) as day
from common_schema.numbers
where n between 1 and 30
order by day
然後,你可以結合起來,與現有查詢,以獲得期望的結果(我做了一些其他小的變化,以您的查詢將其限制在相關日期範圍和使用DATE()
而不是DATE_FORMAT()
爲簡單起見):
select days.day, coalesce(transactions_rollup.total,0)
from
(
select (current_date() - interval n day) as day
from common_schema.numbers
where n between 1 and 30
) days
left outer join (
select date(transaction_date) as day, sum(amount) as total
from transactions
where transaction_date >= current_date() - interval 30 day
and transation_date < current_date()
group by date(transaction_date)
) transactions_rollup on transactions_rollup.day = days.day
order by days.day
是否'transaction_date'使用DATE數據類型?如果是這樣,'DATE_FORMAT組(transaction.transaction_date,'%c-%d-%Y')'將與'transaction_date組'相同(並且慢於)。除此之外,恐怕目前還不清楚你在問什麼。另外,IMO最好在應用程序級別處理日期格式。這樣客戶可以爲自己選擇格式(或者可以爲他們的地區設置)。 – Strawberry
,但我如何顯示所有日期 –