0

我有一个看起来像这样的表:

record no   firstType  secondtype   win?
1               X          A         1
2               X          A         0
3               X          B         1
4               Y          B         0
5               Y          B         1
6               X          B         1
7               X          B         1

我需要输出的是这个。

firstType   secondType   winCounts
   X           [A,B]     [A:1,B:3]
   Y            [B]      [B:1]

所以请注意 secondType 下的数组如何告诉他们与 firstType 发生在哪里,而 winCounts 下的数组则告诉每个 secondType 有多少次获胜与每个 firstType 一起出现。

我可以使用 ARRAY_AGG 制作数组,但我迷失了任何可能的方式来制作 winCounts 列。

4

2 回答 2

0

这是使用 lambda 方法的更复杂的解决方案,因为为什么不这样做:

SELECT 
    PP.firstType AS "firstType"
,    ARRAY_DISTINCT(
         ARRAY_AGG(PP.secondType)
     ) AS "secondType"

,    ZIP_WITH(
         ARRAY_DISTINCT(
             ARRAY_AGG(PP.secondType)
         ),
         ARRAY_AGG(PP.count_str),
         (x, y) -> x || ':' || y
    ) AS "winCount"
FROM (
  SELECT 
     firstType
  ,  secondType
  ,  CAST(SUM("win?") AS VARCHAR(5))
  FROM dataTable
  WHERE "win?" > 0
  GROUP BY 
     firstType
  ,  secondType
) AS PP (firstType, secondType, count_str)
GROUP BY PP.firstType;
于 2021-03-17T02:20:33.690 回答
0

使用两个级别的聚合:

select firsttype, array_agg(secondtype order by secondtype),
       array_agg(secondtype || ':' || wins order by secondtype)
from (select firsttype, secondtype, sum(win) as wins
      from t
      group by firsttype, secondtype
     ) t
group by firsttype;
于 2021-03-17T01:10:08.177 回答