通用 Table 表达式 [CTE] 和 INNER JOIN

Common Table Expression [CTE] and INNER JOIN

我的问题很简单。这是我的代码:

 WITH P1 as  
(
SELECT (count(*)) as Premier_trimestre
FROM import.dvf1,
    (SELECT commune FROM import.dvf1) as commune
WHERE   date_mutation BETWEEN '2020-01-01' AND '2020-03-31' 
 GROUP BY dvf1.commune
)
, P2 as  
(
SELECT (count(*)) as Deuxieme_trimestre
FROM import.dvf1, (select commune FROM import.dvf1) as commune
WHERE   date_mutation BETWEEN '2020-04-01' AND '2020-06-30' 
 GROUP BY dvf1.commune
)


    SELECT * 
FROM
     P1 t1
     INNER JOIN 
     P2 t2
     ON t1.commune = t2.commune

当我 运行 它时,我得到:

ERROR:  column t1.commune does not exist
LINE 23:      ON t1.commune = t2.commune
                ^
SQL state: 42703
Character: 471

我不明白 why.I 尝试重命名公社,移动它等,但我找不到解决方法。

CTE 仅产生一个名为 Premier_trimestreDeuxieme_trimestre 的列。

如果您想包含 import.dvf1 中的公社列,则需要将其包含在 CTE 的 SELECT 列表中。

您还创建了 table 与自身与此部分 FROM import.dvf1, (SELECT commune FROM import.dvf1) 的交叉连接,这很可能是查询永远耗时的原因。

认为您的意图是:

WITH P1 as  
(
  SELECT dvf1.commune, -- this "exposes" the commune column
         count(*) as Premier_trimestre
  FROM import.dvf1
  WHERE dvf1.date_mutation BETWEEN '2020-01-01' AND '2020-03-31' 
  GROUP BY dvf1.commune
)
, P2 as 
(
  SELECT dvf1.commune,  
         count(*) as Deuxieme_trimestre
  FROM import.dvf1
  WHERE dvf1.date_mutation BETWEEN '2020-04-01' AND '2020-06-30' 
  GROUP BY dvf1.commune
)
SELECT * 
FROM P1     
  JOIN P2 ON p1.commune = p2.commune

但是,您可以通过使用 filtered 来大大简化这个过程 聚合:

SELECT commune, 
       count(*) filter (where extract(month from dvf1.date_mutation) in (1,2,3)) as Premier_trimestre, 
       count(*) filter (where extract(month from dvf1.date_mutation) in (4,5,6)) as Deuxieme_trimestre
FROM import.dvf1 
WHERE dvf1.date_mutation BETWEEN '2020-01-01' AND '2020-06-30'  -- this covers both ranges
GROUP dvf1.commune