我知道我的问题标题不对,抱歉。我真正想做的是: 我有2个表,即账户表和历史表如下 - 帐户表
BranchID | AccountNo
101 | 123456
102 | 123456
102 | 123457
历史表
BranchID | AccountNo EmployeeName | EmployeeType
101 | 123456 | Mr. ABC | PMO
101 | 123456 | Mr. TRY | RO
101 | 123456 | Mr. OPR | Ref
102 | 123456 | Mr. WER | PMO
102 | 123456 | Mr. CVB | Ref
102 | 123457 | Mr. QSR | PMO
102 | 123457 | Mr. LIT | RO
102 | 123457 | Mr. GHK | Ref
我希望合并后的结果为 -
BranchID | AccountNo | PMOName | ROName | RefName
101 | 123456 | Mr. ABC | Mr. TRY | Mr. OPR
102 | 123456 | Mr. WER | | Mr. CVB
102 | 123457 | Mr. QSR | Mr. LIT | Mr. GHK
我怎样才能做到这一点?
答案 0 :(得分:0)
以下查询应该获取所需的详细信息。它会做的是 - 遍历所有帐户,然后根据员工类型获取不同的员工姓名。你也可以用连接来做。
SELECT account.branchid BranchID,
account.accountno AccountNo,
(SELECT employeename
FROM history
WHERE account.branch_id = history.branch_id
AND account.accountno = history.accountno
AND history.employeetype = 'PMO'
) PMOName,
(SELECT employeename
FROM history
WHERE account.branch_id = history.branch_id
AND account.accountno = history.accountno
AND history.employeetype = 'RO'
) ROName,
(SELECT employeename
FROM history
WHERE account.branch_id = history.branch_id
AND account.accountno = history.accountno
AND history.employeetype = 'Ref'
) RefName
FROM account
;
答案 1 :(得分:0)
这是基本的透视查询:
select *
from account join history using (branchid, accountno)
pivot (max(employeename) for employeetype in ('PMO' pmo, 'RO' ro, 'Ref' ref))
order by branchid, accountno
BRANCHID ACCOUNTNO PMO RO REF
-------- --------- ---------- ---------- ----------
101 123456 Mr. ABC Mr. TRY Mr. OPR
102 123456 Mr. WER Mr. CVB
102 123457 Mr. QSR Mr. LIT Mr. GHK