代码之家  ›  专栏  ›  技术社区  ›  Punit S

Postgres:按两列分组-按分组包括所有唯一的组合,0表示空计数

  •  3
  • Punit S  · 技术社区  · 8 年前

    我有一张名为cases的表格,如下所示

    os      device      event_time
    Android     Mobile      <Tstamp>
    Android     Tablet      <Tstamp>
    Windows     PC          <Tstamp>
    Linux       PC          <Tstamp>
    

    我需要如下输出:

    os         device    events_count
    Android    Mobile      10
    Android    Tablet      22
    Android    PC          0
    Windows    Mobile      0
    Windows    Tablet      0
    Windows    PC          40
    Linux      Mobile      0
    Linux      Tablet      0
    Linux      PC          21
    

    原始表不包含任何具有(Android、PC)、(Windows、Mobile)等组合的行,但我希望输出的这些行的计数为零。正常的group by查询没有提供这些信息,可能是因为原始表根本没有这些组合。

    select os, device, count(event_time)
    from cases
    group by os, device;
    
    2 回复  |  直到 8 年前
        1
  •  4
  •   Thorsten Kettner    8 年前

    首先选择所有操作系统/设备组合,然后再次外部连接表:

    select o.os, d.device, count(e.events_count)
    from (select distinct os from events) o
    cross join (select distinct device from events) d
    left join events e on e.os = o.os and e.device = d.device
    group by o.os, d.device
    order by o.os, d.device;
    

    (对于此类数据,通常有一个OS表和一个设备表。您可以交叉连接这些表,然后外部连接事件表。)

        2
  •  1
  •   Radim Bača    8 年前

    我会使用 cross join

    select t.os, t.device, count(c.os)
    from 
    (
      select os, device
      from
      (
        select distinct os from cases
      ) t1
      cross join 
      (
        select distinct device from cases
      ) t2
    ) t 
    left join cases c on t.os = c.os and 
                         t.device = c.device
    group by t.os, t.device