查找修复小sql查询的帮助

qcbq4gxm  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(371)

我需要一个查询来返回过去21天的时间条目列表,按成员id排序,然后按开始时间排序,然后将每行的开始时间与前一行的结束时间进行比较,然后显示开始时间大于前一行结束时间的行。
不幸的是,我对sql的所有知识都不是很了解,到目前为止,我的查询返回了一个错误,我不知道需要修改/添加/删除什么来修复它。
下面是我开始使用的视图的一个示例(想象一下这有几千行)。起始视图
当我运行下面的查询时,我得到了按我想要的方式排列的数据。

SELECT
t.time_recID AS id
,t.time_recID AS time_recid
,LOWER(t.Member_ID) AS member_id
,CAST(t.Time_Start_UTC AS DATETIME) AS evt_start
,CAST(t.Time_End_UTC AS DATETIME) AS evt_end
,LAG(t.Time_End_UTC,1,0) OVER (PARTITION BY t.Member_ID ORDER BY t.Time_Start_UTC) AS prev_evtend
FROM v_evt_time AS t
WHERE DATEADD (Day, -21, CURRENT_TIMESTAMP) <= t.Date_Start
ORDER BY member_id, evt_start
OFFSET 0 ROWS

查询结果接近
但是当我在where子句中添加一行来比较evt\u start和prev\u evtend列时,就像这样…

WHERE DATEADD (Day, -21, CURRENT_TIMESTAMP) <= t.Date_Start
AND evt_start < prev_evtend

我得到一个错误,上面写着,列名“evt\u start”无效。列名“prev\u evtstart”无效。
我需要做什么来修复查询以返回所需的结果?非常感谢您的帮助,并提前表示感谢。

bbmckpt7

bbmckpt71#

列名 evt_start 以及 prev_evtend 在定义它们的select语句中不可用。
可以按如下方式使用公共表表达式:

With entries as (
SELECT
t.time_recID AS id
,t.time_recID AS time_recid
,LOWER(t.Member_ID) AS member_id
,CAST(t.Time_Start_UTC AS DATETIME) AS evt_start
,CAST(t.Time_End_UTC AS DATETIME) AS evt_end
,LAG(t.Time_End_UTC,1,0) OVER (PARTITION BY t.Member_ID ORDER BY t.Time_Start_UTC) AS prev_evtend
FROM v_evt_time AS t
WHERE DATEADD (Day, -21, CURRENT_TIMESTAMP) <= t.Date_Start
ORDER BY member_id, evt_start
OFFSET 0 ROWS)
select * 
from entries
WHERE DATEADD (Day, -21, CURRENT_TIMESTAMP) <= t.Date_Start
AND evt_start < prev_evtend

在功能上相当于原始查询之上的查询:

select *
from (
SELECT
t.time_recID AS id
,t.time_recID AS time_recid
,LOWER(t.Member_ID) AS member_id
,CAST(t.Time_Start_UTC AS DATETIME) AS evt_start
,CAST(t.Time_End_UTC AS DATETIME) AS evt_end
,LAG(t.Time_End_UTC,1,0) OVER (PARTITION BY t.Member_ID ORDER BY t.Time_Start_UTC) AS prev_evtend
FROM v_evt_time AS t
WHERE DATEADD (Day, -21, CURRENT_TIMESTAMP) <= t.Date_Start
ORDER BY member_id, evt_start
OFFSET 0 ROWS) sub
WHERE DATEADD (Day, -21, CURRENT_TIMESTAMP) <= t.Date_Start
AND evt_start < prev_evtend

相关问题