MySql 单表,选择过去 7 天并包含空行

2023-05-24数据库问题
2

本文介绍了MySql 单表,选择过去 7 天并包含空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我在 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 天并包含空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Mysql目录里的ibtmp1文件过大造成磁盘占满的解决办法
ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致...
2025-01-02 数据库问题
151

按天分组的 SQL 查询
SQL query to group by day(按天分组的 SQL 查询)...
2024-04-16 数据库问题
77

SQL 子句“GROUP BY 1"是什么意思?意思是?
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)...
2024-04-16 数据库问题
62

MySQL groupwise MAX() 返回意外结果
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)...
2024-04-16 数据库问题
13

MySQL SELECT 按组最频繁
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)...
2024-04-16 数据库问题
16

在 Group By 查询中包含缺失的月份
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)...
2024-04-16 数据库问题
12