使用sql配置单元比较两列中的值并在条件基上返回值
我有两列,我想得到一个基于两者比较的输出。我的数据有点像:使用sql配置单元比较两列中的值并在条件基上返回值,sql,hadoop,Sql,Hadoop,我有两列,我想得到一个基于两者比较的输出。我的数据有点像: Customer Id status 100 A 100 B 101 B 102 A 103 A 103 B 因此,客户可以有状态a或B,或者两者都有,我必须根据客户id将其划分为状态。如果状态A和B返回快乐,如果只有A,返回平均值,如果只有B返回悲伤。尝试以下查询 SELECT DISTINCT Custom
Customer Id status
100 A
100 B
101 B
102 A
103 A
103 B
因此,客户可以有状态a或B,或者两者都有,我必须根据客户id将其划分为状态。如果状态A和B返回快乐,如果只有A,返回平均值,如果只有B返回悲伤。尝试以下查询
SELECT DISTINCT Customer_Id,
(CASE WHEN COUNT(*) OVER(PARTITION BY Customer_Id) > 1 THEN 'happy'
WHEN Tstatus = 'A' THEN 'Avg'
ELSE 'Sad'END) AS New_Status
FROM @table1
GROUP BY Customer_Id,Tstatus
如果客户Id和状态是唯一的组合,则 步骤1:确定a或b的用例
SELECT customer id
,CASE WHEN avg(case when [status] ='A' then 0 else 2 end)
FROM [Your Table]
group by[customer id]
第二步是将平均值放入结果中:如下所示
SELECT customer id
,CASE WHEN (avg(case when [status] ='A' then 0 else 2 end)) = 1 THEN 'happy' ELSE WHEN (avg(case when [status] ='A' then 0 else 2 end)) = 0 THEN 'Avg' ELSE 'Sad' END
FROM [Your Table]
group by[customer id]
我只想这样做:
select customer_id,
(case when min(status) <> max(status) then 'happy'
when min(status) = 'A' then 'avg'
else 'sad'
end)
from t
where status in ('A', 'B')
group by customer_id
选择客户id,
(最小(状态)最大(状态)然后为“快乐”时的情况)
当最小值(状态)=“A”时,则为“平均值”
还有“悲伤”
(完)
从t
其中状态为('A','B')
按客户id分组
是否有一列保存状态值?你考虑使用案例吗?