1

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

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和参考范围内吗?

4

3 回答 3

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
于 2013-05-06T05:07:40.413 回答
1

如何使用加入?

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
于 2013-05-06T05:05:38.663 回答
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
于 2013-05-06T05:10:29.587 回答