yun*_*ark 2 sql sqlite lag lead over-clause
我在 SQLite 中对Codility / 练习 6 SQL / SqlEventsDelta 的解决方案在本地数据库浏览器中有效,但在在线 Codility 测试编辑器中无效。我该如何解决这个问题?我想使用我自己的 SQLite 代码:
WITH cte1 AS
(
SELECT *, CASE WHEN e2.event_type = e2.prev THEN 0
WHEN e2.event_type = e2.next THEN 0
ELSE 1 END AS grp
FROM (SELECT *, LAG(e1.event_type) OVER(ORDER BY (SELECT 1)) AS prev , LEAD(e1.event_type) OVER(ORDER BY (SELECT 1)) AS next FROM events e1) e2
)
,cte2 AS
(
SELECT cte1.event_type, cte1.time, cte1.grp, cte1.value - LAG(cte1.value) OVER(ORDER BY cte1.event_type, cte1.time) AS value
FROM cte1
WHERE cte1.grp = 0
ORDER BY cte1.event_type, cte1.time
)
SELECT c2.event_type, c2.value
FROM cte2 c2
WHERE (c2.event_type, c2.time) IN (
SELECT c2.event_type, MAX(c2.time) AS time
FROM cte2 c2
GROUP BY c2.event_type)
GROUP BY c2.event_type
ORDER BY c2.event_type, c2.time
Run Code Online (Sandbox Code Playgroud)
它在 DB Browser for SQLite Version 3.12.2 上运行,没有错误:
event_type | value
-----------+-----------
2 | -5
3 | 4
Execution finished without errors.
Result: 2 rows returned in 7ms
Run Code Online (Sandbox Code Playgroud)
但在 Codility 测试编辑器(SQLite 版本 3.11.0)上我收到错误:
| Compilation successful.
| Example test: (example test)
| Output (stderr):
| error on query: ...
| ...
| ...,
| details: near "(": syntax error
| RUNTIME ERROR (tested program terminated with exit code 1)
Detected some errors.
Run Code Online (Sandbox Code Playgroud)
小智 6
我尝试使用一种天真的方法。我知道由于有很多子查询,这对性能非常不利,但这里的问题是 PostgreSQL 的“DISTINCT ON”,但是我得到了 100%
希望你喜欢!
select distinct on (event_type) event_type, result * -1
from (select event_type, value, lead(value) over (order by event_type) - value result
from (select *
from events
where event_type in (select event_type
from events
group by event_type
having count(event_type) >= 2)
order by event_type, time desc) a) b
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5253 次 |
| 最近记录: |