1

我尝试创建一个简单的 SQL 来跟踪 query_history 的使用,但是在使用tableandgenerator函数(x下面命名的 CTE)创建我的时间段时遇到了麻烦。

使用我的时间段限制 query_history 时,我根本没有得到任何结果,所以过了一会儿,我硬编码了一个 SQL 以给出相同的结果(y下面命名的 CTE),这很好。

为什么不x工作?据我所知xy产生相同的结果?

要测试示例首先按原样运行代码,这不会产生任何结果。然后注释该行x as timeslots并取消注释该行y as timeslots,这将给出所需的结果。

with 
x as (
    select
        dateadd('min',seq4()*10,dateadd('min',-60,current_timestamp())) f,
        dateadd('min',(seq4()+1)*10,dateadd('min',-60,current_timestamp())) t
    from table(generator(rowcount => 6))
), 
y as (
    select
        dateadd('min',n*10,dateadd('min',-60,current_timestamp())) f,
        dateadd('min',(n+1)*10,dateadd('min',-60,current_timestamp())) t
    from (select 0 n union all select 1 n union all select 2 union all select 3 
          union all select 4 union all select 5)
)

--select * from x;
--select * from y;

select distinct 
    user_name,
    timeslots.f
from snowflake.account_usage.query_history, 
   x as timeslots
   --y as timeslots
where start_time >= timeslots.f
and start_time < timeslots.t
order by timeslots.f desc;

(我知道代码不是最优的,这只是为了说明问题)

4

1 回答 1

2

序列

返回一个单调递增的整数序列,带回绕。环绕发生在整数宽度(1、2、4 或 8 字节)的最大可表示整数之后。

如果需要完全有序、无间隙的序列,请考虑使用 ROW_NUMBER 窗口函数。

为了:

with x as (
    select
        dateadd('min',seq4()*10,dateadd('min',-60,current_timestamp())) f,
        dateadd('min',(seq4()+1)*10,dateadd('min',-60,current_timestamp())) t
    from table(generator(rowcount => 6))
)
SELECT * FROM x;

应该:

with x as (
    select
        (ROW_NUMBER() OVER(ORDER BY seq4())) - 1 AS n,
        dateadd('min',n*10,dateadd('min',-60,current_timestamp())) f,
        dateadd('min',(n+1)*10,dateadd('min',-60,current_timestamp())) t
    from table(generator(rowcount => 6))
)
SELECT * FROM x;
于 2022-03-04T18:12:29.607 回答