Sql 如何在不重复代码的情况下获得x值

Sql 如何在不重复代码的情况下获得x值,sql,Sql,有可能这样做吗 create table t(a int, b int); insert into t values (1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3); select * from t; a | b ---------- 1 | 1 1 | 2 1 | 3 2 | 1 2 | 2 2 |

有可能这样做吗

create table t(a int, b int); insert into t values (1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3); select * from t; a | b ---------- 1 | 1 1 | 2 1 | 3 2 | 1 2 | 2 2 | 3 3 | 1 3 | 2 3 | 3 select max(case when a = 1 then b else 0 end) as q, max(case when b = 1 then a else 0 end) as c, ( max(case when a = 1 then b else 0 end) + max(case when b = 1 then a else 0 end) ) as x from t 不能使用在SELECT子句的同一级别上提供的别名

你有两个选择:

通过直接使用表达式 查询:

select max(case when a = 1 then b else 0 end) as q, max(case when b = 1 then a else 0 end) as c, (q + c) as x from t
select
  max(case when a = 1 then b else 0 end) as q,
  max(case when b = 1 then a else 0 end) as c,
  (max(case when a = 1 then b else 0 end) + max(case when b = 1 then a else 0 end)) as x
from t
通过在子查询中换行 查询:

select max(case when a = 1 then b else 0 end) as q, max(case when b = 1 then a else 0 end) as c, (q + c) as x from t
select
  max(case when a = 1 then b else 0 end) as q,
  max(case when b = 1 then a else 0 end) as c,
  (max(case when a = 1 then b else 0 end) + max(case when b = 1 then a else 0 end)) as x
from t

不幸的是,你不能这么做

别名不能在创建它们的同一级别中使用


我认为临时表是必要的。

同样在SQLServer2005+中,您可以使用CTE

SELECT  q, 
        c,
        q + c as x
FROM
(
  select
      max(case when a = 1 then b else 0 end) as q,
      max(case when b = 1 then a else 0 end) as c
    from t
) d

1答案可能因SQL供应商而异。MySQL?神谕SQL Server?2我打赌一个临时表包含前两列,然后从中选择两列加上新列,可以完成itTNX 100x!子查询是我一直在寻找的。