您可以使用下面的查询。这是一个有效的SQL Fiddle
SELECT CASE WHEN RN=1 THEN IDNumber END IDNumber,
CASE WHEN RN=1 THEN Amount END Amount,
Address, City, State, Zip
FROM
(
SELECT A.IDNumber, A.Amount,
B.Address, B.City, B.STATE, B.Zip,
RN = Row_number() over (partition BY A.IDNumber
ORDER BY B.IDNumber)
FROM tableA A
LEFT JOIN tableB B ON A.IDNumber = B.IDNumber
) X
ORDER BY IDNumber, RN
它给出了这个输出
IDNumber 金额 ADDRESS CITY STATE ZIP
1 200.1 1 公共道路 Gotham AX 19281
(null) (null) 秘密蝙蝠洞 Gotham AX 19281
(null) (null) 海外隐匿处未指定 ?? 不适用
2 312.45 John Woo Lane Trespass TX 12345
(null) (null) 地址 City State Sq-123
当给出这个样本表时
CREATE TABLE TableA(
IDNumber int, Amount money)
CREATE TABLE TableB(
IDNumber int,
Address varchar(max),
City varchar(max),
State varchar(max),
Zip varchar(max))
INSERT TableA SELECT
1,200.10 union all select
2,312.45
INSERT TableB SELECT
1, '1 Public Road', 'Gotham', 'AX', '19281' union all select
1, 'Secret Batcave', 'Gotham', 'AX', '19281' union all select
1, 'Overseas Hideaway', 'Unspecified', '??', 'n/a' union all select
2, 'John Woo Lane', 'Trespass', 'TX', '12345' union all select
2, 'Address', 'City', 'State', 'Sq-123'