【问题标题】:SQL query with array of counts?带有计数数组的 SQL 查询?
【发布时间】:2021-03-17 01:08:01
【问题描述】:

我有一个如下所示的表格:

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 列。

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。

标签: sql array-agg


【解决方案1】:

使用两个级别的聚合:

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;

【讨论】:

    【解决方案2】:

    这是一个使用 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      • 1970-01-01
      相关资源
      最近更新 更多