使用自左连接传递聚合函数列

时间:2010-11-25 05:05:38

标签: sql mysql postgresql join left-join

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

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   |

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

无需创建临时表,只需将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 ...

答案 1 :(得分:1)

听起来您需要使用window functions,请参阅this示例。

示例:

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