How to use a calculated column by another calculated column

旧时模样 提交于 2020-07-08 20:40:12

问题


I have a query in Sqlite that involves a complicated column calculation, let's say:

SELECT 1+1 AS a;

I want to have this calculation selected as a, but I also need to use it as a component of another calculation:

SELECT 1+1 AS a, a+2 AS b;

Unfortunately this produces the error:

Error: no such column: a

I know that I could simply repeat the calculation again for b:

SELECT 1+1 AS a, 1+1+2 AS b;

But assuming 1+1 is some complicated and expensive operation, is there any way that I can reference it later in the SELECT without having to recalculate it?


回答1:


You need to use a sub-query.

SELECT c.d AS a, c.d + 2 AS b
FROM
  (SELECT 1+1 AS d) c

Result

| a | b |
---------
| 2 | 4 |



回答2:


In addition to all nice examples by others - this works in Oracle:

SELECT a, a+2 b From
(
 SELECT 1+1 a From dual
)
/

Output:

A | B
-----
2 | 4



回答3:


See if you can do it something like this (using a subquery for the table)

Select t.a+2 as b
    FROM (Select 1+1 as a from xyz) t 


来源:https://stackoverflow.com/questions/14244029/how-to-use-a-calculated-column-by-another-calculated-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!