如果我正確理解你的問題,這裏的技巧是,你需要2點LEFT JOIN
聲明並在選擇ISNULL
。下面,第二個LEFT JOIN
只查看沒有AccountCategory的行。這會產生你的Table3。該解決方案假設Table1的AccountCategory不能爲空/空。
設置:
DECLARE @Table1 TABLE
(
CostCenter INT,
AccountCategory VARCHAR(10)
)
DECLARE @Table2 TABLE
(
CostCenter INT,
AccountCategory VARCHAR(10),
Flag VARCHAR(10)
)
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8601, 'ABC1');
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8601, 'ABC1');
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8601, 'ABC2');
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8601, 'ABC3');
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8601, 'ABC4');
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8602, 'ABC1');
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8602, 'ABC1');
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8602, 'ABC2');
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8602, 'ABC3');
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8602, 'ABC4');
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8603, 'ABC1');
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8603, 'ABC1');
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8603, 'ABC2');
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8603, 'ABC3');
INSERT INTO @Table1 (CostCenter, AccountCategory) VALUES (8603, 'ABC4');
INSERT into @Table2 (CostCenter, AccountCategory, Flag) VALUES (8601, 'ABC1', 'Yes');
INSERT into @Table2 (CostCenter, AccountCategory, Flag) VALUES (8602, null, 'Yes');
INSERT into @Table2 (CostCenter, AccountCategory, Flag) VALUES (8603, null, 'Yes');
查詢:
SELECT t1.CostCenter, t1.AccountCategory, ISNULL(t2a.Flag, t2b.Flag) AS Flag
FROM @Table1 t1
LEFT JOIN @Table2 t2a ON ISNULL(t2a.AccountCategory,'') = t1.AccountCategory AND t1.CostCenter = t2a.CostCenter
LEFT JOIN @Table2 t2b ON ISNULL(t2b.AccountCategory,'') = '' AND t1.CostCenter = t2b.CostCenter
結果:
CostCenter AccountCategory Flag
8601 ABC1 Yes
8601 ABC1 Yes
8601 ABC2 NULL
8601 ABC3 NULL
8601 ABC4 NULL
8602 ABC1 Yes
8602 ABC1 Yes
8602 ABC2 Yes
8602 ABC3 Yes
8602 ABC4 Yes
8603 ABC1 Yes
8603 ABC1 Yes
8603 ABC2 Yes
8603 ABC3 Yes
8603 ABC4 Yes
能否請你分享你正在試圖獲得該樣品的輸入輸出? – Mureinik
是這樣的:'SELECT * FROM [表1] LEFT JOIN [表2]在[TABLE1] [成本中心] = [表2] [成本中心] AND([表1] [科目類別] = [表2]。。。。 [Account Category] OR([Table1]。[Account Category] IS NULL AND [Table2]。[Account Category] IS NULL))''也許? –
是「表3」所需的輸出? – Jayvee