2014-01-31 35 views
1

我想顯示的最近30天 這裏完整列表是我的查詢:如何顯示上個月的日期列表?

select Distinct DATE_FORMAT(transactions.transaction_date,'%c-%d-%Y') as transaction_date,sum(amount)as Amount from transactions group by DATE_FORMAT(transactions.transaction_date,'%c-%d-%Y') 

,這裏是我的查詢結果:

enter image description here

,但我想

transaction_date Amount 
1-01-2014   0 
2-01-2014   0 

到如此我如何得到完整的結果?

+0

是否'transaction_date'使用DATE數據類型?如果是這樣,'DATE_FORMAT組(transaction.transaction_date,'%c-%d-%Y')'將與'transaction_date組'相同(並且慢於)。除此之外,恐怕目前還不清楚你在問什麼。另外,IMO最好在應用程序級別處理日期格式。這樣客戶可以爲自己選擇格式(或者可以爲他們的地區設置)。 – Strawberry

+0

,但我如何顯示所有日期 –

回答

1

這裏的典型方法是首先編寫一個查詢,獲取您想要的日期列表,然後使用外部聯接將該事務處理範圍內的日期的交易金額關聯起來。

我的建議是安裝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 
0

您需要的是一個生成器視圖(類似於PostgreSQL generate_series()函數可獲得的視圖),其中包含無間隙月份的所有日期。不幸的是,MySQL沒有這樣的功能,所以你需要pregenerate the dates in some calendar table,然後把你的原始查詢留給它,或者依靠一些big enough table

+0

...或使用UNION,或在應用程序級別處理缺少日期的邏輯(如果這實際上是問題) – Strawberry

相關問題