我在这里在stackoverflow上搜索了类似的问题,但是我不明白如何使这项工作,我想做的事情…
因此,我想从数据库中获取最近7天的交易记录,并获取总销售额,并且如果某天没有数据,还包括空行。
到目前为止,我所拥有的:http : //sqlfiddle.com/#!2/f4eda/6
输出:
| PURCHASE_DATE | AMOUNT | |---------------|--------| | 2014-04-25 | 19 | | 2014-04-24 | 38 | | 2014-04-22 | 19 | | 2014-04-19 | 19 |
我想要的是:
| PURCHASE_DATE | AMOUNT | |---------------|--------| | 2014-04-25 | 19 | | 2014-04-24 | 38 | | 2014-04-23 | 0 | | 2014-04-22 | 19 | | 2014-04-21 | 0 | | 2014-04-20 | 0 | | 2014-04-19 | 19 |
任何帮助表示赞赏:)
只需将子查询与所需日期和使用日期放在一起left outer join:
left outer join
select d.thedate, coalesce(SUM(amount), 0) AS amount from (select date('2014-04-25') as thedate union all select date('2014-04-24') union all select date('2014-04-23') union all select date('2014-04-22') union all select date('2014-04-21') union all select date('2014-04-20') union all select date('2014-04-19') ) d left outer join transactions t on t.purchase_date = d.thedate and vendor_id = 0 GROUP BY d.thedate ORDER BY d.thedate DESC;