你好,我在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;