如何通过查询使我的计数组返回零值?

时间:2018-02-10 16:12:34

标签: sql postgresql group-by count

抱歉我的英文!

我在postgresql数据库中有这个Attribution表:

表归因:

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

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

感谢您的建议☺️

2 个答案:

答案 0 :(得分:0)

您可以添加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

答案 1 :(得分:0)

您可以将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;