无法以预期格式格式化 trino sql 查询

问题描述 投票:0回答:1

我有一个疑问-

WITH dataset(ns, tid, nid) AS ( values ('PQR',  'ITKT20254',  'A'),
('PQR', 'ITKT20223',    'A'),
('PQR', 'ABCD23456',    'B'),
('PQR', 'ABCD54321',   'B'),
('PQR', 'ITKT21111',    'A') )

select ns,nid, 
    cast(row(tradelist , res1) as row(tid array(varchar),res varchar)) as finalMap 
from
  (select ns,nid,tradelist,res1 
   from (
      select ns,nid,
          array_agg(cast(tid  as varchar)) as tradelist,
          'not include' as  res1
      from dataset 
      group by ns, nid 
     union 
      select ns,nid, 
          array_agg(cast(tid  as varchar)) as tradelist,
          'include' as  res1 
      from dataset 
      group by ns, nid
    )
   )

得到结果-

ns      nid      finalMap
PQR     A   {tid=\[ITKT20254, ITKT20223, ITKT21111\], res=not include}
PQR     A   {tid=\[ITKT20254, ITKT20223, ITKT21111\], res=include}
PQR     B   {tid=\[ABCD23456, ABCD54321\], res=not include}
PQR     B   {tid=\[ABCD23456, ABCD54321\], res=include}

预期产出-

ns      nid      finalMap
PQR     A   [{tid=[ITKT20254, ITKT20223, ITKT21111], res=not include},{tid=[ITKT20254, ITKT20223, ITKT21111], res=include}]
PQR     B   [{tid=[ABCD23456, ABCD54321], res=not include},{tid=[ABCD23456, ABCD54321], res=include}]

我正在尝试修改查询以获得上述格式。但在 array_agg 函数中出现错误

sql presto trino
1个回答
0
投票

不知道为什么你没有使用我之前的答案,但这次尝试一下:

select ns, nid,
       transform(array['include', 'not include']
               ,t -> cast(row(tids, t) as row(tid array(varchar), res varchar))) as finalMap
from (select ns,
             nid,
             array_agg(tid) tids
      from dataset
      group by ns, nid);

既然您生成了

include/not include
对,您就可以使用
transform
来生成相应的行

输出:

ns 尼德 最终地图
PQR A [{tid=[ITKT20254, ITKT20223, ITKT21111], res=包括}, {tid=[ITKT20254, ITKT20223, ITKT21111], res=不包括}]
PQR B [{tid=[ABCD23456, ABCD54321], res=包括}, {tid=[ABCD23456, ABCD54321], res=不包括}]
© www.soinside.com 2019 - 2024. All rights reserved.