我有 SNOWFLAKE 数据库表,其中包含客户及其交易类型:
customer_id type
1 a
1 a
2 b
2 b
2 b
3 a
3 b
3 a
在输出时,我需要不同的客户 ID 和交易类型:
customer_id type
1 a
2 b
3 mixed
我的代码不起作用:
SELECT
"customer_id",
CASE WHEN type = 'a' THEN "a"
WHEN type = 'b' THEN "b"
ELSE "mixed" END OVER (PARTITION BY "customer_id" ) AS "type"
FROM CUSTOMERS
最佳答案
您需要聚合和一个 CASE
表达式来检查每个 customer_id
的不同 type
数量:
SELECT customer_id,
CASE WHEN COUNT(DISTINCT type) = 1 THEN MAX(type) ELSE 'mixed' END AS type
FROM CUSTOMERS
GROUP BY customer_id;
编写 CASE
表达式的另一种方法是:
CASE WHEN MIN(type) = MAX(type) THEN MAX(type) ELSE 'mixed' END AS type
我假设 type
不可为空。
关于sql - 在 SNOWFLAKE SQL 中选择和聚合不同 id 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69885493/