gpt4 book ai didi

sql - Postgres : Group by two columns - group by includes all unique combinations with 0 for null counts

转载 作者:行者123 更新时间:2023-11-29 12:02:42 24 4
gpt4 key购买 nike

我有一个名为 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)等组合的行,但我寻求输出使这些行的计数为零。正常的分组查询没有给我这些可能是因为原始表根本没有这些组合。

select os, device, count(event_time)
from cases
group by os, device;

最佳答案

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

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;

(不过,对于此类数据,您通常有一个操作系统表和一个设备表。您可以交叉连接这些数据,然后向外连接您的事件表。)

关于sql - Postgres : Group by two columns - group by includes all unique combinations with 0 for null counts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48495287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com