PostgreSQL CROSS JOIN 查询问题

问题描述

我想改进以下查询:

WITH calendar as (
      SELECT d
      FROM generate_series(
'2015-01-01'::timestamp,'2020-12-01'::timestamp,interval '1 month'
) d
     )
     
SELECT c.d::date AS ord_date,n.id,coalesce(nb_cit,0) as nb_cit
FROM (SELECT distinct t.id from "data".taxonomie t where id = '30092') n CROSS JOIN
     calendar c
left join 
(select date_trunc('month',i2.date_d) as mon,count(c2.id) as nb_cit
from "data".inventaire i2,"data".citation c2 where i2.id = c2.id_inv and c2.id_taxo = '30092'
group by mon) s
on c.d = s.mon

当我设置一个 id(在 from 和 left join 中)时它会起作用。但想法是让所有 id 得到结果。

如果我不设置这个标识符,无论标识符是什么,我都会得到相同的结果。 我想我必须从左连接中取出“count(c2.id)”,但我不知道该怎么做。

欢迎提供帮助!

最好的问候, 马蒂亚斯

解决方法

我认为您只想在子查询中按 id 进行聚合:

SELECT c.d::date AS ord_date,n.id,coalesce(s.nb_cit,0) as nb_cit
FROM (SELECT DISTINCT t.id FROM "data".taxonomie t) n CROSS JOIN
     calendar c LEFT JOIN
     (SELECT c2.id_taxo,date_trunc('month',i2.date_d) as mon,count(c2.id) as nb_cit
      FROM "data".inventaire i2 JOIN
           "data".citation c2 
           ON i2.id = c2.id_inv 
      GROUP BY c2.id_taxo,mon
     ) s
     ON c.d = s.mon AND n.id = s.id_taxo;

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...