在雪花中按内部视图排序以创建唯一 ID

Order By inside view in snowflake to create unique ID

我的代码为每行生成唯一 ID(800 万行数据)。如果我将 ORDER BY 放在 CREATE VIEW AS... 中,行的顺序会保持不变吗?

预期结果将是始终具有相同的 ID,无论谁在何时执行视图。 我读到 ORDER BY inside view 语句不保证静态排序,在视图外使用 ORDER BY 将允许它工作。

雪花 dwh 的工作方式是否不同?从我在执行计划中看到的情况来看,它似乎是直截了当的:从最低的嵌套查询开始,并在执行操作时向上移动)

Maybye 而不是视图我应该使用 table?

--sample data
create or replace table determin_sort as (

select uuid,position,val1,val2 
from values ('u98rutu', 66788, 1, 3), 
            ('u999etd', 66788, 2,3), 
            ('voko225', 66788, 2,3),
            ('pp29ccd', 229, 20, 30), 
            ('aa55jmw', 229, 2, 3), 
            ('1ojcugi7', 8994, 2, 30), 
            ('2yrhbf',8994,20,3) 

            v(uuid,position,val1,val2)
);


--view
create or replace view v_determin_sort as

SELECT 'L'||row_number() over (order by position) as LID 
        uuid, 
        position,
        val1,
        val2 FROM (SELECT 
                   row_number() over (partition by position order by uuid) as rn, * 
                   FROM determin_sort
                   QUALIFY row_number() over (partition by position order by uuid) = 1
                   ORDER BY UUID);
--query the view
SELECT * FROM v_determin_sort ORDER BY LID;

无法保证每次视图 运行 时同一行的 LID 编号相同,除非 window 函数中的 ORDER BY 是唯一的.

如果您要在视图中按 LID 排序,我相信在这种特定情况下您会没事,因为您首先计算 LID 列然后对其进行排序。尽管我建议不要向视图添加排序操作,因为排序是一项昂贵的操作。

My code generates unique ID per row (8 milion rows of data). If I put ORDER BY inside CREATE VIEW AS... will that keep rows order the same?

您在视图的子 select 中拥有的 ORDER BY UUID 是没有意义的,正如关心顺序(ROW_NUMBER 的)的行所证明的那样拥有ORDER BY

Expected result would be to have always the same ID no matter who and when executes the view. I read that ORDER BY inside view statement doesn't garantee static sorting and using ORDER BY outside the view will allow it to work.

ORDER BY 在那个时候视图会 "order the data",但是如果你将 table 加入其他 table,与其他 table首先,观点的顺序意义不大。

SELECT t.*, v.*
FROM table_name AS t
JOIN view_name AS v ON t.uuid = v.uuid

数据可以按照它喜欢的任何方式对这些行进行排序。如果此查询中添加了一个订单,例如 ORDER BY t.column_a 通过在视图内订购创建了哪些值,则全部为演示。

更重要的是,如果您希望 ID 为 stable,则需要在 ROW_NUMBERS 中使用的 ORDER BY 中使用的值是 s table(也就是 UUID 中的示例数据没有重复项)。

CREATE OR REPLACE VIEW v_determin_sort AS
SELECT 
    'L' || row_number() OVER (ORDER BY position) AS lid 
    ,uuid
    ,position
    ,val1
    ,val2
FROM (
    SELECT 
        row_number() OVER (PARTITION BY position ORDER BY uuid) AS rn /* this row is not needed as the QUALIFY is doing the work */
        ,uuid
        ,position
        ,val1
        ,val2
    FROM determin_sort
    QUALIFY row_number() OVER (PARTITION BY position ORDER BY uuid) = 1
    ORDER BY UUID /* this order by does nothing */
);

这将给出相同的结果,只要 table 中的数据不变,如果新的 positions 或 'UUID' 是 inserted/deleted,您将得到这些变化的不同结果。此外,UUID 似乎是一个字符串,这似乎是一个奇怪的排序值,因为 UUID 通常在相对于时间设置的位中是随机的,所以为什么一个 UUID 更有效,因为 best/lastest/most 想要任何 position