CREATE TABLE TableX
(ID varchar(20),
NO varchar(20),
DIA varchar(20));
INSERT INTO TableX
VALUES
('20210101','A01','100'),
('20210101','A02','200'),
('20210102','A01','100'),
('20210103','A01','100'),
('20210103','A01','100');
CREATE TABLE TableA
(ID varchar(20),
NO varchar(20),
DIA varchar(20));
INSERT INTO TableA
VALUES
('20210102','X01','100'),
('20210102','X02','150');
-- 解法一
SELECT X.ID,X.NO,X.DIA
FROM TableX AS X
WHERE X.ID NOT IN (SELECT B.ID FROM TableA AS B)
UNION ALL
SELECT A.ID,A.NO,A.DIA
FROM TableA AS A
ORDER BY X.ID,X.NO
-- 解法二
SELECT A.ID,
CASE WHEN X.NO IS NOT NUll THEN X.NO ELSE A.NO END AS NO,
CASE WHEN X.DIA IS NOT NUll THEN X.DIA ELSE A.DIA END AS DIA
FROM TableX AS A
LEFT JOIN TableA AS X ON X.ID = A.ID
-- 解法三
select X.ID
, coalesce(A.NO, X.NO) AS NO
, coalesce(A.DIA, X.DIA) AS DIA
from TableX AS X
left join TableA AS A
on X.ID = A.ID
我也來插一腳XD...
-- 解法四
SELECT a.ID
,isNull(b.NO,a.NO) NO
,isNull(b.DIA,a.DIA) DIA
FROM TableX a
left join TableA b on a.ID = b.ID
SELECT X.ID AS ID ,
CASE
WHEN A.NO IS NOT NULL
THEN A.NO
ELSE X.NO
END AS NO ,
CASE
WHEN A.DIA IS NOT NULL
THEN A.DIA
ELSE X.DIA
END AS DIA
FROM X
LEFT JOIN A
ON A.ID = X.ID