【发布时间】:2018-08-01 22:24:34
【问题描述】:
我正在尝试使用临时表来简化我的查询。一开始我使用 WITH,如果我没有专门加入每个表,则无法识别。处理此查询的最佳方法是什么?这个语法有什么问题?
对于购买最多(作为客户在其整个生命周期内)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
【问题讨论】:
-
不同的数据库以不同的方式处理这个问题...postgres 将使用 with 语法,而 mysql 8.0 及更高版本可以工作,但不能使用早期版本。您已将其标记为 mysql 和 postgres...介意指定您使用的数据库吗?
-
Postgres。你能告诉我应该如何使用 Postgres 吗?
-
在 google 中输入“带有子句的 postgres”并按照第一个结果(应该是 postgressql: 文档)。也称为 cte 或公用表表达式
-
用分号 (
;) 结束您的语句。 -
应该可以与
WITH一起使用。更高效的方法是将“临时表”作为子选择放入FROM子句中。
标签: sql postgresql temp-tables