根据行值将列名提取为字符串的sql
我有一个表格,数据格式如下根据行值将列名提取为字符串的sql,sql,hive,hiveql,Sql,Hive,Hiveql,我有一个表格,数据格式如下 custid scr1 scr2 scr3 1111 1 2 3 2222 4 3 2 3333 4 5 3 我需要为每个custid选择列名,按行值排序,如下所示 custid str 1111 scr3,scr2,scr1 2222 scr1,scr2,scr3 3333 scr2,scr1,scr3 实现这一目标的最佳方法是什么这是我首
custid scr1 scr2 scr3
1111 1 2 3
2222 4 3 2
3333 4 5 3
我需要为每个custid选择列名,按行值排序,如下所示
custid str
1111 scr3,scr2,scr1
2222 scr1,scr2,scr3
3333 scr2,scr1,scr3
实现这一目标的最佳方法是什么这是我首选的解决方案
select custid
,concat_ws (',',scr[0].col2,scr[1].col2,scr[2].col2) as str
from (select custid
,sort_array
(
array
(
struct(-scr1,'scr1')
,struct(-scr2,'scr2')
,struct(-scr3,'scr3')
)
) as scr
from mytable
) t
另一种方法是使用
union all
取消表数据的驱动,并基于scr1、scr2、scr3值分配行号。然后按custid聚合以生成csv值
with rownums as
(select t.*,row_number() over(partition by custid order by cast(scr as int) desc) as rnum
from (select custid,scr1 as scr,'scr1' as col from mytable
union all
select custid,scr2 as scr,'scr2' as col from mytable
union all
select custid,scr3 as scr,'scr3' as col from mytable
) t
)
select custid,concat(max(case when rnum=1 then col end),',',max(case when rnum=2 then col end),',',max(case when rnum=3 then col end))
from rownums
group by custid
试试这个
第一步。首先将初始查询集取消Pivot到BASEQ中
BASEQ:
select * from UT_TEST
UNPIVOT
(
SCRVAL for SCRNAME in (
scr1 as 'scr1',
scr2 as 'scr2',
scr3 as 'scr3'
)
)
结果集:
1111 scr1 1
1111 scr2 2
1111 scr3 3
2222 scr1 4
2222 scr2 3
2222 scr3 2
3333 scr1 4
3333 scr2 5
3333 scr3 3
1111 scr3,scr2,scr1
2222 scr1,scr2,scr3
3333 scr2,scr1,scr3
第二步:然后使用Listag
这是密码
WITH BASEQ
AS
(
select * from UT_TEST
UNPIVOT
(
SCRVAL for SCRNAME in (
scr1 as 'scr1',
scr2 as 'scr2',
scr3 as 'scr3'
)
)
)
SELECT BASEQ.CUSTID, LISTAGG(BASEQ.SCRNAME,',') WITHIN GROUP (ORDER BY BASEQ.SCRVAL DESC) FINALCOL FROM BASEQ
GROUP BY BASEQ.CUSTID;
最终结果集:
1111 scr1 1
1111 scr2 2
1111 scr3 3
2222 scr1 4
2222 scr2 3
2222 scr3 2
3333 scr1 4
3333 scr2 5
3333 scr3 3
1111 scr3,scr2,scr1
2222 scr1,scr2,scr3
3333 scr2,scr1,scr3
mysql或配置单元..?主要寻找配置单元解决方案。您可以有更多的列,还是只显示3列?只显示3列。参数类型不匹配“scr3”:函数SORT_数组的参数1必须是数组,但找到了数组。这是一个测试过的代码(我测试过的最早版本是配置单元1.1.0)。您使用的配置单元版本是什么?配置单元2.3。我的create table查询是create table mytable作为选择'1111'作为custid,'1'作为scr1,'2'作为scr2,'3'作为scr3 union select'2222','4','3','2'union select'3333','4','5','3',奇怪的是,它抱怨第一个参数是双参数。请描述下表给出的内容。。custid string scr1 string scr2 string scr3 string没有这样的版本,显然应该小于1.1.0您是否看到了
hive
标记?我想是的。由于答案不相关,请将其删除。
+--------+----------------+
| custid | str |
+--------+----------------+
| 1111 | scr3,scr2,scr1 |
| 2222 | scr1,scr2,scr3 |
| 3333 | scr2,scr1,scr3 |
+--------+----------------+