在 SQL 的表中选择具有受限时间戳差异(以秒为单位)的行

Selecting rows with constrained time-stamp differences (in seconds) in tables in SQL

我在 SQL 中有一个名为 visit_times 的 table,就像这样

    name   time_stamp
    Allen  2015-02-13 07:10:54
    Allen  2015-02-13 07:10:58
    Allen  2015-02-13 07:11:02
    Mary   2015-02-17 10:45:33
    Mary   2015-02-17 10:45:39
    Mary   2015-02-17 10:45:43
    ...    

我需要 select 来自“名称”列的名称,其中 所有 “time_stamp”中的行连续差异(以秒为单位)列等于某个值。使用 LAG() 命令,我尝试将其编码如下

WITH cte AS
(
  SELECT  name, 
          DATEDIFF(second, LAG(time_stamp) OVER (PARTITION BY name ORDER BY time_stamp), time_stamp) AS visit_gap 
  FROM customer_transactions
)
SELECT cte.name
FROM cte
GROUP BY cte.name
HAVING MIN(cte.visit_gap) = 10 AND MAX(cte.visit_gap) = 4;

我期望得到如下结果:

---------
| name  |
---------
| Allen |
---------

但是它没有任何输出!我得到错误:在预先编写的模板中:Incorrect parameter count in the call to native function 'DATEDIFF'

我不知道如何解决这个问题。任何提示将不胜感激。

SQL 查询按特定顺序处理(快速搜索“sql query order of operations”给了我这个 nice result)。列别名 visit_gap 只能从 order by 子句开始重复使用。这解释了你的语法错误。

通常的解决方案是在 where 子句中复制 visit_gap 表达式,从而得到:

SELECT  name, 
        time_stamp - LAG(time_stamp) OVER (PARTITION BY name ORDER BY time_stamp) AS visit_gap
FROM visit_times
WHERE time_stamp - LAG(time_stamp) OVER (PARTITION BY name ORDER BY time_stamp) = 4;

但是,这会给您一个新的错误,指出 LAG() 函数不能出现在 where 子句中...

Windowed functions can only appear in the SELECT or ORDER BY clauses.

为了将 LAG()visit_gap 计算与过滤(where 子句)分开,您可以使用 common table expression (CTE). Also, use the DATEDIFF() function (function documentation) 来计算日期之间的差异。

with cte as
(
  SELECT  name, 
          datediff(second, LAG(time_stamp) OVER (PARTITION BY name ORDER BY time_stamp), time_stamp) AS visit_gap
  FROM visit_times
)
select cte.name,
       cte.visit_gap --> column alias is available now!
from cte;

在 where 子句中添加过滤器会得到最终结果:

with cte as
(
  SELECT  name, 
          datediff(second, LAG(time_stamp) OVER (PARTITION BY name ORDER BY time_stamp), time_stamp) AS visit_gap
  FROM visit_times
)
select cte.name,
       cte.visit_gap --> column alias is available now!
from cte
where cte.visit_gap > 4;

Fiddle 解释了所有中间步骤!