mysql - 具有多个条件的 SELECT GROUP

标签 mysql sql database

我有下面这张表,想要获取数量的最小值、数量的最大值、数量的第一个值和数量的最后一个值。新表应按日期分组,间隔为 1 天。

id  item    quantity    date
1   xLvCm   2           2020-01-10 19:15:03
1   UBizL   4           2020-01-10 20:16:41
1   xLvCm   1           2020-01-10 21:21:12
1   xLvCm   3           2020-01-11 11:14:00
1   UBizL   1           2020-01-11 15:01:10
1   moJEe   4           2020-01-12 00:15:50
1   moJEe   1           2020-01-12 02:11:23
1   UBizL   1           2020-01-12 04:16:17
1   KiZoX   3           2020-01-13 10:10:02
1   KiZoX   2           2020-01-13 19:05:40
1   KiZoX   1           2020-01-13 20:14:33

这是预期的表格结果

min(quantity)   max(quantity)   first(quantity) last(quantity)    date
1               4               2               1                 2020-01-10 19:15:03
1               3               3               1                 2020-01-11 11:14:00
1               4               4               1                 2020-01-12 00:15:50
1               4               3               1                 2020-01-13 10:10:02

我尝试过的SQL查询是
从表名 GROUP BY 日期中选择 MIN(数量)、MAX(数量)、FIRST(数量)、LAST(数量)
我不知道如何包含数量的第一个和最后一个值并按天分组(如 10、11、12、13),而不是像 (2020-01-10 19:15:03) 这样的日期

最佳答案

说明您正在使用的数据库工具非常重要,因为每个工具都提供不同的功能。但如果你使用 Snowflake,我会尝试以下方法:

select distinct day(date) as day_of_month,
       min(quantity) over (partition by day(date) order by date range between unbounded preceding and UNBOUNDED FOLLOWING) min_quantity, 
       max(quantity) over (partition by day(date) order by date range between unbounded preceding and UNBOUNDED FOLLOWING) max_quantity ,
       last_value(QUANTITY) over (partition by day(date) order by date range BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) as last_quantity,  
       first_value(QUANTITY) over (partition by day(date) order by date range BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) as first_quantity
from demo_db.staging.test

值得注意的是,这是一个代价高昂的查询。如果您的 table 很大,这可能会花费很长时间。

关于mysql - 具有多个条件的 SELECT GROUP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60024435/

相关文章:

mysql - 从 MySQL 中获取按两列数据分组的数据的查询

MySQL 引用不存在的表创建表

mysql - 子查询和联合

php - 关于我的数据库 MySQL 和 Android Studio 的问题

sql - 如何用外连接和笛卡尔积连接三个表

c# - Entity Framework 6 DbUpdateConcurrencyException 将新行添加到数据库时

php mysql查询问题

php - PDO 的 AJAX 升级 ($qry_result)

mysql - 寻找更好的解决方案 - 与类型字符串比较的长列表 AND 运算符

sql - 显示今天、明天、一周和一个月的产品