简体   繁体   English

在雪花中用“LEVEL”重写查询

[英]Rewrite a query with "LEVEL" in snowflake

How can I write this SQL query into SNOWFLAKE?如何将此 SQL 查询写入 SNOWFLAKE?

SELECT LEVEL lv FROM DUAL CONNECT BY LEVEL <= 3;从 DUAL CONNECT BY LEVEL <= 3 中选择 LEVEL lv;

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 ).您可以使用 CONNECT BY ( https://docs.snowflake.com/en/sql-reference/constructs/connect-by.html ) 和此处 ( https://docs.snowflake.com/en ) 找到一些好的起点/user-guide/queries-hierarchical.html )。

Snowflake is also supporting recursive CTEs. Snowflake 还支持递归 CTE。

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:对于固定的小乘数,例如 3,您可以只枚举数字:

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:与 Oracle 的区别在于:

  • 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:根据@Danil Suhomlinov 的帖子,我们可以进一步简化使用 COLUMN1 处理特殊表双单列:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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