如何在PostgreSQL中创建临时表?

时间:2018-08-01 22:24:34

标签: sql postgresql temp-tables

我正在尝试使用临时表来简化查询。在开始时,我使用了WITH,如果我没有专门连接每个表,则无法识别。处理此查询的最佳方法是什么?这种语法有什么问题?

The data base

对于购买了最多(作为客户的一生中的商品)standard_qty纸的帐户,有多少个帐户的总购买量还更多?

create temp table t1 as (
  SELECT
    a.id as account_id,
    SUM(o.standard_qty) as all_std_qty
  FROM
    accounts a
    JOIN orders o ON (a.id = o.account_id)
  GROUP BY
    1
  order by
    2 desc
  limit
    1
)
create temp table t2 as (
  SELECT
    a.id as account_id,
    SUM(o.total) as total_purchases
  FROM
    accounts a
    JOIN orders o ON (a.id = o.account_id)
  GROUP BY
    1
)
create temp table t3 as (
  SELECT
    t1.account_id,
    t2.total_purchases as total_pur FROM
    t1
    JOIN t2 
    ON (t1.account_id = t2.account_id)
)

SELECT
  count(a.id) as count_ids
FROM
  accounts a
  JOIN orders o ON (a.id = o.account_id)
WHERE
  o.total > t3.total_pur

2 个答案:

答案 0 :(得分:0)

我尝试过WITH,但无法正常工作:

WITH t1 as (
 SELECT
   a.id as account_id,
   SUM(o.standard_qty) as all_std_qty
 FROM
   accounts a
   JOIN orders o ON (a.id = o.account_id)
 GROUP BY
   1
 order by
   2 desc
 limit
   1
), t2 as (
 SELECT
   a.id as account_id,
   SUM(o.total) as total_purchases
 FROM
   accounts a
   JOIN orders o ON (a.id = o.account_id)
 GROUP BY
   1
), t3 as (
 SELECT
   t1.account_id,
   t2.total_purchases as total_pur FROM
   t1
   JOIN t2
   ON (t1.account_id = t2.account_id)
)
SELECT
 count(a.id) as count_ids
FROM
 accounts a
 JOIN orders o ON (a.id = o.account_id)
WHERE
 o.total > t3.total_pur

答案 1 :(得分:0)

我认为您错过了与表t3的连接,并且在问题所在的where子句中使用了它,请您尝试使用以下查询

WITH t1 as (
 SELECT
   a.id as account_id,
   SUM(o.standard_qty) as all_std_qty
 FROM
   accounts a
   JOIN orders o ON (a.id = o.account_id)
 GROUP BY
   1
 order by
   2 desc
 limit
   1
), t2 as (
 SELECT
   a.id as account_id,
   SUM(o.total) as total_purchases
 FROM
   accounts a
   JOIN orders o ON (a.id = o.account_id)
 GROUP BY
   1
), t3 as (
 SELECT
   t1.account_id,
   t2.total_purchases as total_pur FROM
   t1
   JOIN t2
   ON (t1.account_id = t2.account_id)
)
SELECT
 count(a.id) as count_ids
FROM
 accounts a
 JOIN orders o ON (a.id = o.account_id)
 inner join t3 on a.id=t3.account_id
WHERE
 o.total > t3.total_pur