问题
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