简体   繁体   中英

Rewrite a query with "LEVEL" in snowflake

How can I write this SQL query into SNOWFLAKE?

SELECT LEVEL lv FROM DUAL CONNECT BY LEVEL <= 3;

You can find some good starting points by using CONNECT BY ( https://docs.snowflake.com/en/sql-reference/constructs/connect-by.html ) and here ( https://docs.snowflake.com/en/user-guide/queries-hierarchical.html ).

Snowflake is also supporting recursive CTEs.

It seems like you want to duplicate the rows three times. For a fixed, small multiplier such as 3, you could just enumerate the numbers:

select c.lv, a.*
from abc a
cross join (select 1 lv union all select 2 union all select 3) c

A more generic approach, in the spirit of the original query, uses a standard recursive common-table-expression to generate the numbers:

with cte as (
    select 1 lv
    union all select lv + 1 from cte where lv <= 3
)
select c.lv, a.*
from abc a
cross join cte c 

There is level in snowflake. The differences from Oracle are:

  • In snowflake it's neccesary to use prior with connect by expression.
  • And you can't just select level - there should be any existing column in the select statement.

Example:

SELECT LEVEL, dummy FROM 
    (select 'X' dummy ) DUAL 
CONNECT BY prior LEVEL <= 3;

LEVEL   DUMMY
1   X
2   X
3   X
4   X

As per @Danil Suhomlinov post, we can further simplify using COLUMN1 for special table dual single column:

SELECT LEVEL, column1 FROM dual CONNECT BY prior LEVEL <= 3; LEVEL | COLUMN1 ------+-------- 1 |
2 |
3 |
4 |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM