您可以使用下面的查詢。這裏的工作一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 Amount ADDRESS CITY STATE ZIP
1 200.1 1 Public Road Gotham AX 19281
(null) (null) Secret Batcave Gotham AX 19281
(null) (null) Overseas Hideaway Unspecified ?? n/a
2 312.45 John Woo Lane Trespass TX 12345
(null) (null) Address 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'
您正在使用什麼RDBMS? SQL服務器,MySQL,甲骨文?你能發佈一些樣本數據和期望的結果嗎? – Taryn