【发布时间】:2021-03-03 07:30:51
【问题描述】:
我有这张表,它显示了设备在某个区域和特定位置所做的点。
working_date device points area location
19-06-2020 a 1 x xa
19-06-2020 a 2 x xa
19-06-2020 a 3 x xa
19-06-2020 a 4 x xa
20-06-2020 a 5 x xa
20-06-2020 a 6 x xa
20-06-2020 a 7 x xa
20-06-2020 a 8 x xa
20-06-2020 a 9 x xa
我想获取按区域和位置分组的当前点、平均点和最大点。如果我选择任何一天,当前数量将显示最近工作日期的数量。同时,平均数量将显示设备工作的总体平均值。最后,最大数量将显示设备完成的整体最大点。
根据我上面的表格,如果我选择 21-06-2020 那么想要的结果:
working_date area location device current_qty avg_qty max_qty
21-06-2020 x xa a 5 4,5 5
平均数量来自total_qty / total_of_date,而最大数量来自所有日期的最大数量。
到目前为止我构建的查询是:
select t1.working_date, t1.device, t1.area, t1.location, t1.points_qty, t1.total_date,
sum(t1.pile_qty) over(partition by t1.working_date) / sum(t1.total_date) over(partition by t1.working_date) as avg_qty,
max(t1.pile_qty) over(partition by t1.working_date) as max_qty
from (
select working_date, device, points, area, location, count(points) as points_qty, count(distinct working_date) as total_date
from table1 group by device, area, location
group by working_date, device, points, area, location) t1
group by working_date, device, points, area, location, pile_qty, total_date
通过上面的查询,我得到:
working_date area location device current_qty avg_qty max_qty
21-06-2020 x xa a 5 5 5
我应该如何编写查询以获得所需的结果?
提前致谢。
【问题讨论】:
-
您想要的输出显示 21 日,这在示例数据中不可用。所以计算出来的数据很难看懂……
-
意思是,如果我选择任何一天,想要的结果总是给我最新的working_date
-
数量值从何而来?
-
通过点数
-
我不知道 PostgreSQL,但是在 MS SQL Server 中聚合函数返回与聚合列相同的数据类型;我建议使用
sum(...) * 1.0 / sum(...)。
标签: sql postgresql window-functions