我有下面这张表,想要获取数量的最小值、数量的最大值、数量的第一个值和数量的最后一个值。新表应按日期分组,间隔为 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/