多行转换多列:使用str_to_map 或者 case when

本文介绍了两种在SQL中处理数据的方法。第一种是使用`str_to_map`函数结合`collect_set`和`concat_ws`进行数据聚合和转换,以获取每个学院在不同授权状态(S1, S2, S3)的计数。第二种方法是利用`case when`语句进行条件聚合,分别计算各状态的最高计数。这两种方法在数据分析和报表生成中非常实用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:利用str_to_map函数

with  instute_temp3_result_1 as (
  select
    t4.instun_name,
    str_to_map(
      concat_ws(
        '&',
        collect_set(
          concat_ws('=', t4.auth_result, t4.auth_result_count)
        )
      ),
      '&',
      '='
    ) as map_remote
  from
    instute_temp3_result t4
  group by
    t4.instun_name
)
select
  t5.instun_name,
  nvl(t5.map_remote ['S1'], 0) as S1,
  nvl(t5.map_remote ['S2'], 0) as S2,
  nvl(t5.map_remote ['S3'], 0) as S3
from
  instute_temp3_result_1  t5

方法二:利用case when函数

select
  t4.instute_name,
  max(
    case
      when t4.auth_result = 'S1' then t4.auth_result_count
      else null
    end
  ) as S1,
  max(
    case
      when t4.auth_result = 'S2' then t4.auth_result_count
      else null
    end
  ) as S2,
  max(
    case
      when t4.auth_result = 'S3' then t4.auth_result_count
      else null
    end
  ) as S3
from
  instute_temp3_result t4
group by
  t4.instute_name

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值