如何在另一个结果列的expression式中重用结果列
例:
SELECT (SELECT SUM(...) FROM ...) as turnover, (SELECT SUM(...) FROM ...) as cost, turnover - cost as profit
当然,这是无效的(至less在Postgres),但如何在不重写子查询两次查询中实现相同的?
像这样:
SELECT turnover, cost, turnover - cost as profit from ( (SELECT SUM(...) FROM ...) as turnover, (SELECT SUM(...) FROM ...) as cost ) as partial_sums
你可以像这样重复使用这个查询:
WITH TURNOVER AS ( SELECT SUM(...) FROM ...) ), COST AS( SELECT SUM(...) FROM ... ) SELECT * FROM( SELECT TURNOVER.sum as SUM_TURNOVER FROM TURNOVER,COST WHERE .... ) AS a
这相当于:
SELECT * FROM( SELECT TURNOVER.sum as SUM_TURNOVER FROM ( SELECT SUM(...) FROM ...) )AS TURNOVER, ( SELECT SUM(...) FROM ... )AS COST WHERE .... ) AS a
这里有一点要注意。 第一种方法更具可读性和可重用性,但第二种方法可能会更快,因为数据库可能会select更好的scheme。
也许sql“with”子句可以提供帮助,如http://orafaq.com/node/1879 (其他数据库如Postgres也是这样做的,不只是oracle)。
干杯! 安德烈
其实我在这方面做了很多工作,打了很多砖墙,但最后想出了一个答案 – 更多的是黑客 – 但它工作得很好,减less了我的查询阅读开销90%….
所以,而不是复制相关的查询多次从子查询中检索多个列,我只是用concat所有的值我想返回到一个逗号分隔的varchar,然后在应用程序中再次展开它们…
所以,而不是
select a,b, (select x from bigcorrelatedsubquery) as x, (select y from bigcorrelatedsubquery) as y, (select z from bigcorrelatedsubquery) as z from outertable
我现在呢
select a,b, (select convert(varchar,x)+','+convert(varchar,x)+','+convert(varchar,x)+',' from bigcorrelatedsubquery) from bigcorrelatedquery) as xyz from outertable group by country
我现在有三个相关的“标量”值,但只需要执行相关子查询一次而不是三次。
SELECT turnover, cost, turnover - cost FROM ( SELECT (SELECT ...) as turnover, (SELECT ...) as cost ) as Temp
我认为以下将起作用:
SELECT turnover, cost, turnover-cost as profit FROM (SELECT 1 AS FAKE_KEY, SUM(a_field) AS TURNOVER FROM some_table) a INNER JOIN (SELECT 1 AS FAKE_KEY, SUM(a_nother_field) AS COST FROM some_other_table) b USING (FAKE_KEY);
没有在动物身上testing – 你会成为第一! 🙂
分享和享受。
你可以像这样使用用户定义的variables
SELECT @turnover := (SELECT SUM(...) FROM ...), @cost := (SELECT SUM(...) FROM ...), @turnover - @cost as profit
使用交叉申请或外部申请。
SELECT Calc1.turnover, Calc2.cost, Calc3.profit from cross apply ((SELECT SUM(...) as turnover FROM ...)) as Calc1 cross apply ((SELECT SUM(...) as cost FROM ...)) as Calc2 /* Note there is no from Clause in Calc 3 below. This is how you can "stack" formulas like in excel. You can return any number of columns, not just one. */ cross apply (select Calc1.turnover - Calc2.cost as profit) as Calc3
这是相当古老,但我遇到了这个问题,看到这个post,但没有设法解决我的问题,使用给定的答案,所以我最终到达这个解决scheme:
如果您的查询是:
SELECT (SELECT SUM(...) FROM ...) as turnover, (SELECT SUM(...) FROM ...) as cost, turnover - cost as profit
你可以把它变成一个子查询,然后使用如下的字段:
SELECT *,(myFields.turnover-myFields.cost) as profit FROM ( SELECT (SELECT SUM(...) FROM ...) as turnover, (SELECT SUM(...) FROM ...) as cost ) as myFields
我不完全确定,如果这是一个不好的方式做事情,但performance明智,似乎没关系,我查询超过224,000
logging花了1.5秒,不知道它后来变成了由DB相同的子查询的2倍。