【问题标题】:How can I make my count-group by query return the zero values?如何通过查询使我的计数组返回零值?
【发布时间】:2018-02-10 16:12:34
【问题描述】:

对不起我的英语!

我的 postgresql 数据库中有这个属性表:

表属性:

Id  | name | date
1  | peter | 2018-02-20
2  | peter | 2018-02- 28
3  | peter | 2018-02-20
3  | John  | (empty)
4  | mike  | 2018-02-18
5  | mike  | 2018-02-19
6  | mike  | 2018-02-19
7  | mike  | 2018-02- 02
8  | jack  | (empty)
9  | jack  | (empty)
10 | jack |(empty)

我希望我的请求给我:

结果:

Id | name | count(Id)
1 | peter | 2
2 | john  | 0
3 | Mike  | 3
4 | jack  | 0

这是我的查询:

Select attribution.id, attribution.name, count(attribution.id)
From attribution
Where date< '2018-02-21'
And date> '2018-02-15'
Group by attribution.id, attribution.name

不幸的是,这个查询没有返回零。它返回我:

Id | name  | count(Id)
1  | peter | 2
2  | Mike  | 3

所以我的问题是: 如何让我的查询返回零值?

感谢您的建议☺️

【问题讨论】:

    标签: sql postgresql group-by count


    【解决方案1】:

    您可以添加or date is null谓词和计数日期而不是id

    Select attribution.id, attribution.name, count(attribution.date)
    From attribution
    Where (date < '2018-02-21'
           And date > '2018-02-15')
          or date is null
    Group by attribution.id, attribution.name
    

    【讨论】:

      【解决方案2】:

      您可以将where 条件移动到select,因此所有名称都存在:

      Select a.id, a.name, 
             sum(case when date < '2018-02-21' and date > '2018-02-15' then 1 else 0 end)
      From attribution a
      Group by a.id, a.name;
      

      或者,在 Postgres 中,更简洁的是:

      Select a.id, a.name, 
             sum( (date < '2018-02-21' and date > '2018-02-15')::int )
      From attribution a
      Group by a.id, a.name;
      

      而且,如果顺序列很重要:

      Select row_number() over (order by a.id) as seqnum,
             a.id, a.name, 
             sum( (date < '2018-02-21' and date > '2018-02-15')::int )
      From attribution a
      Group by a.id, a.name;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-29
        • 2015-08-14
        • 1970-01-01
        • 1970-01-01
        • 2022-11-10
        • 1970-01-01
        • 2017-03-12
        • 1970-01-01
        相关资源
        最近更新 更多