问题描述
我有一张看起来像这样的表格:
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 列的任何可能方法。
解决方法
使用两级聚合:
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;
,
这是一个更复杂的 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,count_str)
GROUP BY PP.firstType;