【问题标题】:How to include zeros and null in the aggregation COUNT with some constraint如何在具有某些约束的聚合 COUNT 中包含零和 null
【发布时间】:2021-07-23 06:52:37
【问题描述】:

我有下表,我必须计算cust, prod, month 组合中before_avgafter_avg 之间的量化数量。我必须确保 1 月和 12 月的计数是 null,因为 1 月之前没有月份,12 月之后没有月份,并且您无法检查值是否介于 nullint 之间。而且我还需要确保在本月剩下的时间里,如果before_avgafter_avg 之间没有数量,我需要显示0。我尝试了简单的方法,例如使用 between 子句。这只是过滤掉了0null 的任何计数。我还尝试将一月和十二月分开,并尝试使计数显示为零。我实际上查看了 Stack Overflow,人们说我们可以通过 left join right join 来实现它。我试过了,因为我在 group by 中有three keys,所以它似乎不太好用。

我知道你们很多人可能会建议像nvl 这样的函数来完成这项工作,但不幸的是,我只允许使用标准 SQL 语法。

因此,我想就如何处理这个问题征求意见和建议?我可以写查询,但我需要你们的一些想法和想法!

非常感谢!!

以下是我创建的一些示例代码供大家尝试:(这是在 PostgreSQL 中)

create table abc (
    cust varchar(20), 
    prod varchar(20),
    month integer,
    quant integer,
    before_avg integer, 
    after_avg integer) 
    
insert into abc values ('Boo', 'Apple', 1, 399, null, 461); 
insert into abc values ('Boo', 'Apple', 1, 650, null, 461); 
insert into abc values ('Boo', 'Apple', 4,620, 400,303); 
insert into abc values ('Boo', 'Apple', 4,870, 400,303); 
insert into abc values ('Boo', 'Apple', 12,575,482,null);
insert into abc values ('Boo', 'Apple', 12,670,482, null); 

insert into abc values ('Chad', 'Banana', 1, 800, null, 461); 
insert into abc values ('Chad', 'Banana', 1, 445, null, 461); 
insert into abc values ('Chad', 'Banana', 4,456, 400,303); 
insert into abc values ('Chad', 'Banana', 4,237, 400,303); 
insert into abc values ('Chad', 'Banana', 12,523,482,null); 
insert into abc values ('Chad', 'Banana', 12,584,482, null);

【问题讨论】:

    标签: sql postgresql count null


    【解决方案1】:

    我有下表,我必须计算 cust、prod、month 中 before_avg 和 after_avg 之间的 quant 数量

    这听起来像聚合:

    select cust, prod, month,
           count(*) filter (where quant between before_avg and after_avg)
    from abc
    group by cust, prod, month;
    

    您可以在没有过滤器的情况下编写此代码(这似乎很愚蠢,因为filter 是 ISO SQL 标准语法):

    select cust, prod, month,
           sum( (quant between before_avg and after_avg)::int )
    from abc
    group by cust, prod, month;
    

    【讨论】:

    • 这可行,但我认为我也不能使用filter。我需要使用标准语法。当月份为 1 或 12 时,此结果不会产生 null
    • filter 标准语法。 SQL 标准,是的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    相关资源
    最近更新 更多