如何在没有代码重复的情况下获取值x

时间:2013-05-01 08:48:11

标签: 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   |   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
      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

3 个答案:

答案 0 :(得分:5)

您不能使用在ALIAS子句的同一级别上提供的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,
  (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  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 :(得分:1)

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

;WITH cte AS
 (
  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
  )
  SELECT q, c, q + c as x
  FROM cte

答案 2 :(得分:0)

不幸的是,你无法做到这一点。

ALIAS不能在您创建它们的同一级别使用。

我认为临时表是必要的。