【问题标题】:Comparing values in two columns and returning values on conditional bases using sql hive使用 sql hive 比较两列中的值并根据条件返回值
【发布时间】:2018-01-15 10:59:53
【问题描述】:

我有两列,我想根据两者的比较得到一个输出。我的数据有点像:

Customer Id   status
100           A
100           B
101           B
102           A
103           A
103           B

因此,客户可以具有状态 A 或 B,或两者兼有,我必须根据客户 ID 将它们分开以获得状态。如果状态 A 和 B 则返回快乐,如果只有 A,返回 Avg,如果只有 B 返回 Sad。

【问题讨论】:

  • 它是保存状态值的一列吗?你有考虑用case吗?

标签: sql hadoop


【解决方案1】:

试试下面的查询,

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

【讨论】:

    【解决方案2】:

    如果客户 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]
    

    第 2 步将把 avg 转换成结果:像这样

    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]
    

    【讨论】:

      【解决方案3】:

      我会这样做:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多