【问题标题】:How to find the approriate SQL syntax for Snowflake environment?如何为 Snowflake 环境找到合适的 SQL 语法?
【发布时间】:2021-12-08 17:58:28
【问题描述】:

这是我的数据在订单表中的配置方式:

我有 3 个字段:ORDER_ID,即每个 ORDER 的唯一字段(在整个表中只出现一次),USER_KEY,即每个 BUYER 的唯一字段(买家可以下多个订单,并且可以在订单中出现多次表)和 FRUIT,用于标识每个订单已购买的商品。

我需要确定购买了多个相同产品的买家 (USER_KEY)。

我有以下查询来识别这些买家:

      select 
        t.user_key from temp t 
inner join (
        SELECT user_key,
        Count(order_id) as [Minimum of 2 Count] from temp group by user_key, fruit 
    ) it on t.user_key = it.user_key and it.[Minimum of 2 Count] > 1
    group by t.user_key;

但是,此查询在 SNOWFLAKE 中不起作用。有谁知道我可以如何调整这个查询的语法以在 Snowflake 中工作?

谢谢!

【问题讨论】:

    标签: sql snowflake-cloud-data-platform


    【解决方案1】:

    " 引用的标识符 - [] 可能是 Sybase 或 T-SQL 语法:

    select  t.user_key from temp t 
    inner join (
            SELECT user_key,
            Count(order_id) as "Minimum of 2 Count" from temp group by user_key, fruit 
        ) it on t.user_key = it.user_key and it."Minimum of 2 Count" > 1
        group by t.user_key;
    

    无论如何查询都可以重写:

    SELECT DISTINCT user_key
    FROM temp t
    QUALIFY COUNT(order_id) OVER(PARTITION BY user_key, fruit) > 1;
    

    或:

    SELECT DISTINCT user_key
    FROM temp 
    GROUP BY user_key, fruit
    HAVING COUNT(ORDER_ID) > 1;
    

    【讨论】:

    • 非常感谢!像魅力一样工作
    【解决方案2】:

    首先获取用户和水果相同的所有结果并计算这些结果。

    然后在外部查询中过滤结果:

    SELECT 
        user_key
    FROM 
    (
       SELECT
          t1.user_key as user_key,
          count(t1.user_key) as num_user
       FROM
          temp t1
          temp t2
       WHERE
          t1.user_key = t2.user_key
          AND t1.fruit = t2.fruit
       GROUP BY
          t1.user_key
    )
    WHERE
      num_user > 2
    

    【讨论】:

      【解决方案3】:

      我们可以根据您正在查看的列使用 windows 功能或组:

       select user_key, fruit, count(1) from Test1
      group by user_key, fruit
      having count(1)>1;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-27
        • 1970-01-01
        • 2021-05-03
        • 1970-01-01
        • 1970-01-01
        • 2020-04-18
        • 2015-01-21
        • 2019-06-27
        相关资源
        最近更新 更多