SQL - SELECT中的临时变量

时间:2013-05-06 05:01:45

标签: sql variables select

所以我发现自己做了这样的事情:

SELECT
    Foo = 
    CASE
        WHEN a.Foo IS NULL THEN (SELECT x.Foo FROM x WHERE x.Id = a.Id)
        ELSE a.Foo
    END,
    Bar =
    CASE
        WHEN a.Bar IS NULL THEN (SELECT x.Bar FROM x WHERE x.Id = a.Id)
        ELSE a.Bar
    END,
    Alice = 
    CASE
        WHEN a.Alice IS NULL THEN (SELECT x.Alice FROM x WHERE x.Id = a.Id)
        ELSE a.Alice
    END
FROM a INNER JOIN b ON a.X = b.X

看起来不漂亮。所以我想知道是否有任何方法可以创建一个临时变量,如:

WITH Temp AS SELECT * FROM x WHERE x.Id = a.Id

SELECT范围内,并参考它?

3 个答案:

答案 0 :(得分:2)

尝试

SELECT 
       Foo   = COALESCE(a.Foo, x.Foo),
       Bar   = COALESCE(a.Foo, x.Foo),
       Alice = COALESCE(a.Alice, x.Alice)
  FROM a JOIN 
       b ON a.X = b.X LEFT JOIN
       x ON x.Id = a.Id

SELECT 
       COALESCE(a.Foo, x.Foo) Foo,
       COALESCE(a.Foo, x.Foo) Bar,
       COALESCE(a.Alice, x.Alice) Alice
  FROM a JOIN 
       b ON a.X = b.X LEFT JOIN
       x ON x.Id = a.Id

答案 1 :(得分:1)

如何使用join?

SELECT  COALESCE(a.Foo, x.Foo) Foo,
        COALESCE(a.Bar, x.Bar) Bar,
        COALESCE(a.Alice, x.Alice) Alice
FROM    a 
        INNER JOIN b ON a.X = b.X
        LEFT JOIN x ON a.ID = x.ID

答案 2 :(得分:0)

SELECT  CASE WHEN a.Foo IS NULL THEN x.Foo ELSE a.Foo End as Foo,
        CASE WHEN a.Bar IS NULL THEN x.Bar ELSE a.Bar End  as Bar,
        CASE WHEN a.Alice IS NULL THEN x.Alice ELSE a.Alice End as Alice
FROM    a 
        INNER JOIN b ON a.X = b.X
        INNER JOIN x ON a.ID = x.ID