MySql Single Table, Select last 7 days and include empty rows(MySql 单表,选择过去 7 天并包含空行)
问题描述
我在 stackoverflow 上搜索过类似的问题,但我不明白如何进行这项工作,我正在尝试做什么...
I have searched similar problems here on stackoverflow but I could not understand how to make this work, what I'm trying to do...
所以,我想从数据库中获取过去 7 天的交易并获取总销售额,如果某天没有数据,还包括空行.
So, I want to get last 7 days transactions from database and get total sales amount and also include empty rows if there is no data for some day.
到目前为止我所拥有的:http://sqlfiddle.com/#!2/f4eda/6
What I have so far: 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:
Simply put together a subquery with the dates you want and use 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;
这篇关于MySql 单表,选择过去 7 天并包含空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySql 单表,选择过去 7 天并包含空行
基础教程推荐
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- oracle区分大小写的原因? 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 在多列上分布任意行 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
