SQL选择不同的日期和ID计数

时间:2018-10-04 10:36:36

标签: sql postgresql

我的SQL表是

|  date             |  id  |
|     03 Aug 2018   |   1  |
|     03 Aug 2018   |   2  |
|     04 Aug 2018   |   1  |
|     04 Aug 2018   |   3  |
|     05 Aug 2018   |   1  |
|     05 Aug 2018   |   2  |
|     05 Aug 2018   |   3  |

我想得到如下输出

|        date       |  id  | count  |
|     03 Aug 2018   |   1  |    1   |
|     03 Aug 2018   |   2  |    1   |
|     03 Aug 2018   |   3  |    0   |
|     03 Aug 2018   |   4  |    0   |
|     04 Aug 2018   |   1  |    0   |
|     04 Aug 2018   |   2  |    0   |
|     04 Aug 2018   |   3  |    1   |
|     04 Aug 2018   |   4  |    0   |
|     05 Aug 2018   |   1  |    1   |
|     05 Aug 2018   |   2  |    1   |
|     05 Aug 2018   |   3  |    1   |
|     05 Aug 2018   |   4  |    0   |

基本上,我想获取一个不同的日期,ID和它们的计数(如果在特定日期不存在ID,则计数为0)。

我已经尝试过查询

select date, id, count(id) from table group by date,id;

但是输出没有给我想要的结果。有什么方法可以使用SQL查询实现所需的输出?

我会很感激。

1 个答案:

答案 0 :(得分:0)

使用cross join生成行,使用left join引入现有数据。大概,您然后希望聚合计数:

select d.date, i.id, count(t.id)
from (select distinct date from t) d cross join
     (select distinct id from t) i left join
     t
     on t.date = d.date and t.id = i.id
group by d.date, i.id
order by d.date, i.id;

如果计数始终为0或1,则不需要聚合(这会使查询的运行成本更高)。

select d.date, i.id, ( t.id is not null )::int as count
from (select distinct date from t) d cross join
     (select distinct id from t) i left join
     t
     on t.date = d.date and t.id = i.id
order by d.date, i.id;