CREATE TABLE A (
A1 INT,
A2 INT
);
CREATE TABLE B (
B1 INT,
B2 INT
);
CREATE TABLE C (
C1 INT,
C2 INT
);
GO
INSERT INTO A
SELECT 1, 101 UNION ALL
SELECT 2, 102 UNION ALL
SELECT 3, 103 UNION ALL
SELECT 4, NULL UNION ALL
SELECT 5, NULL UNION ALL
SELECT 11, 111 UNION ALL
SELECT 12, 112 UNION ALL
SELECT 13, 113 UNION ALL
SELECT 14, NULL UNION ALL
SELECT 15, NULL;
INSERT INTO C
SELECT 1, 301 UNION ALL
SELECT 2, 302 UNION ALL
SELECT 3, 303 UNION ALL
SELECT 4, 304 UNION ALL
SELECT 5, 305 UNION ALL
SELECT 31, 311 UNION ALL
SELECT 32, 312 UNION ALL
SELECT 33, 313 UNION ALL
SELECT 34, 314 UNION ALL
SELECT 35, 315;
INSERT INTO B
SELECT 1, 301 UNION ALL
SELECT 2, 302 UNION ALL
SELECT 3, 303 UNION ALL
SELECT 4, 304 UNION ALL
SELECT 5, 305 UNION ALL
SELECT 21, 211 UNION ALL
SELECT 22, 212 UNION ALL
SELECT 23, 213 UNION ALL
SELECT 24, 214 UNION ALL
SELECT 25, 215;
GO
SELECT
case when A2 is null then B2
else A2
end AS W,
case when A1 is null and B2=C2 then C.C1
else A1
end AS E
from
C LEFT JOIN A ON (A.A1 = C.C1)
JOIN B ON (B.B2 = C.C2);
W E
----------- -----------
101 1
102 2
103 3
304 4
305 5
(5 行受影响)
你写的也太乱了吧,而且也没描述出想要什么效果?我给你改了一下你看看对不对。
CREATE VIEW ABC
as
slect
W=case
when A2 is null then B2
else A2
end,
E=case
when A1 is null then C1
else A1
end
from A join C on A1=C1 join B on C2=B2
或者简化一下,直接写:
CREATE VIEW ABC
as
slect
W=ISNULL(A2,B2),
E=ISNULL(A1,C1)
from A join C on A1=C1 join B on C2=B2
CREATE VIEW ABC
as
slect
W=ISNULL(A2,B2),
E=ISNULL(A1,C1)
from A
INNER JOIN C ON A1=C1
INNER JOIN B ON C2=B2
(case when A2 is null then B2 else A2 end),
(case when A1 is null then C1 else A1 end)
做连接查询
CREATE VIEW
ABC
as
select
(case
when A2 is null
then B2
else A2
end) as W,
(case
when A1 is null
then c1
else A1
end) as E
from A,B,C where A.a1(+)=C.c1 and C.c2=B.b2
目测我的能达到要求