sql - 在 SNOWFLAKE SQL 中选择和聚合不同 id 的变量

标签 sql database group-by case snowflake-cloud-data-platform

我有 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/

相关文章:

php - 对来自 MySql 的记录进行分组

sql - 在postgres中转换时间戳格式

sql - 具有空记录输入参数的 Postgresql STRICT 函数

database - .NET CF 移动设备应用程序 - 处理潜在离线的最佳方法?

php - Codeigniter 安全删除数据库条目

mysql - 如何从两个表中获取计数结果

sql - 复杂 SQL 连接子查询与前 1 条记录

javascript - 将 .sql 文件转换为 .json 或 javascript 对象或 Sequelize 模型文件的最佳方法

iphone - 管理 iPhone 设备上的大型数据库 : simple sqlite3 coding or CoreData?

python - 如何获取 groupby 中的第一个值,TypeError : first() missing 1 required positional argument: 'offset'