通过自左连接传递聚合函数列

发布于 2024-10-04 16:42:27 字数 750 浏览 5 评论 0原文

我想在列上调用一次聚合函数(成本),并通过自左连接级联它(用于创建行的排列或组合)。这样我算出在连接 O(row^joins) 之后调用它的成本是 O(n) 。从这样的事情开始:

id | cost 
----------
1  |  5   
2  |  10  

我想做一些类似于下面的事情。我可以做类似的事情,选择一个临时表并连接它,但是我想避免使用临时表...

CREATE TEMP TABLE tmp_750309_plans AS (SELECT *, cost(id) as cost  FROM plans WHERE plans.id IN (1,2,...));

SELECT * FROM tmp_750309_plans AS t1 LEFT JOIN tmp_750309_plans AS t2 ON ...

我更愿意做类似的事情:

SELECT id, cost(id) as cost FROM plans AS t1
LEFT JOIN t1 AS t2 
ON t1.id != t2.id
AND ...

要得到这样的东西:

id | cost | id | cost |
-----------------------
1  |  5   |NULL| NULL |
2  |  10  |3   | 15   |

任何帮助将不胜感激。

I would like to call a aggregate function (cost) once on a column and cascade it through the self left joins (used to create a permutation or combination of rows). That way I figure the cost is O(n) apposed to calling it after the joins O(row^joins). Starting with something like this:

id | cost 
----------
1  |  5   
2  |  10  

I would like to do something similar to below. I can do something similar with a select into a temporary table and joining off that but I would like to avoid using a temporary table...

CREATE TEMP TABLE tmp_750309_plans AS (SELECT *, cost(id) as cost  FROM plans WHERE plans.id IN (1,2,...));

SELECT * FROM tmp_750309_plans AS t1 LEFT JOIN tmp_750309_plans AS t2 ON ...

I would prefer to do something like:

SELECT id, cost(id) as cost FROM plans AS t1
LEFT JOIN t1 AS t2 
ON t1.id != t2.id
AND ...

To get something like this:

id | cost | id | cost |
-----------------------
1  |  5   |NULL| NULL |
2  |  10  |3   | 15   |

Any help would be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

轮廓§ 2024-10-11 16:42:27

无需创建临时表,只需使您的 SELECT 成为派生表:

SELECT * 
FROM (
  SELECT *, cost(id) as cost  
  FROM plans 
  WHERE plans.id IN (1,2,...)
) tmp AS t1 LEFT JOIN tmp AS t2 ON ...

或使用公共表表达式的替代解决方案(适用于 PostgreSQL 8.4 及更高版本)

with tmp as (
  SELECT *, cost(id) as cost  
  FROM plans 
  WHERE plans.id IN (1,2,...)
)
SELECT *
FROM tmp as T1
  LEFT JOIN tmp AS t2 ON ...

No need to create the temporary table, just make your SELECT a derived table:

SELECT * 
FROM (
  SELECT *, cost(id) as cost  
  FROM plans 
  WHERE plans.id IN (1,2,...)
) tmp AS t1 LEFT JOIN tmp AS t2 ON ...

or an alternative solution with a common table expression (for PostgreSQL 8.4 and above)

with tmp as (
  SELECT *, cost(id) as cost  
  FROM plans 
  WHERE plans.id IN (1,2,...)
)
SELECT *
FROM tmp as T1
  LEFT JOIN tmp AS t2 ON ...
眸中客 2024-10-11 16:42:27

听起来您需要使用窗口函数请参阅这个示例。

例子:

SELECT id, sum(cost) OVER (ORDER BY cost) FROM t1;

Sounds like you need to make use of window functions see this example.

Example:

SELECT id, sum(cost) OVER (ORDER BY cost) FROM t1;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文