sql - 优化 LAG 查询的输出
问题描述
您好,我在 Ubuntu 上运行 postgresql 10.10。
我的表中有以下数据:
radio | hits | iteration
---------+------+-----------
211 | 1 | 1
1423013 | 1 | 1
2114805 | 1 | 1
2114833 | 1 | 1
2109257 | 1 | 1
126681 | 1 | 2
802802 | 2 | 2
1426801 | 2 | 2
2613847 | 1 | 2
208 | 27 | 2
(10 rows)
radio | hits | iteration
-------+------+-----------
211 | 1 | 1
211 | 24 | 2
211 | 49 | 3
211 | 84 | 4
211 | 131 | 5
211 | 157 | 6
211 | 169 | 7
211 | 181 | 8
211 | 200 | 9
211 | 223 | 10
211 | 244 | 11
211 | 273 | 12
hits 列是累积的,我需要从当前迭代命中中减去以前的迭代命中以确定值的变化。目前我正在使用以下 LAG 查询。
SELECT radio_alias, iteration, radio, hits - LAG ( hits, 1, 0 )
OVER (PARTITION BY radio ORDER BY iteration) AS ithits FROM radios;
这给了我以下输出,这是我所期望的:
radio_alias | iteration | radio | ithits
-------------+-----------+---------+--------
"" | 101 | 205 | 0
"" | 102 | 205 | 7
"" | 103 | 205 | 2
"" | 2 | 208 | 27
"" | 3 | 208 | 38
"" | 4 | 208 | 13
"" | 5 | 208 | 21
我需要做的是从 LAG 查询的输出中选择所有具有最大迭代值的行,理想情况下 SQL 语句会自动确定它,比如 MAX(iteration),如果不是,我可以从我的程序中提供一个变量。
我已经能够使用以下代码使用临时表来解决它,但想知道是否有更优雅的解决方案不涉及临时表。
SELECT radio_alias, iteration, radio, hits - LAG ( hits, 1, 0 )
OVER (PARTITION BY radio ORDER BY iteration) AS ithits INTO TEMP rad_hits FROM radios;
SELECT * FROM rad_hits WHERE iteration = 103 ORDER BY ithits DESC LIMIT 5;
radio_alias | iteration | radio | ithits
-------------+-----------+---------+--------
"" | 103 | 209 | 41
"" | 103 | 211 | 29
"" | 103 | 2109215 | 20
"" | 103 | 210 | 18
"" | 103 | 2109232 | 17
(5 rows)
解决方案
这是做你想做的吗?
SELECT radio_alias, iteration, radio,
hits - LAG ( hits, 1, 0 ) OVER (PARTITION BY radio ORDER BY iteration) AS ithits
FROM radios
ORDER BY iteration DESC
LIMIT 5;
推荐阅读
- javascript - 根据下拉值显示匹配的嵌套子 div
- amazon-redshift - 需要 SQL 调试帮助
- python - csv文件中的所有内容都转换为int64?
- ios - 如何将数据添加到 Firestore 数据库中的特定 uid?
- python-3.x - 从 4 个不同角度融合图像
- sql - 在 Postgres 中将数据从一个表传输到另一个表,两个表具有相同的 id
- python - 您可以在特定行之后删除 .txt 文件的所有行吗?
- excel-formula - 如何将不同列中的值放入Excel中的一列?
- python - 如何更改networkx中的标签名称
- python - 如何使用 jmespath 构造路径以获取值