三种不同的方法:
SQL小提琴
Oracle 11g R2 模式设置:
CREATE TABLE ACCOUNT ( ACCOUNTID, LBKEY ) AS
SELECT 254, 'value254' FROM DUAL
UNION ALL SELECT 401, 'value401' FROM DUAL
UNION ALL SELECT 405, 'value405' FROM DUAL
UNION ALL SELECT 406, 'value406' FROM DUAL;
CREATE TABLE CrossReference ( IDTABLE2, ACCOUNTID, OIDID, VALUE ) AS
SELECT 475, 401, 4, '40000' FROM DUAL
UNION ALL SELECT 476, 405, 4, '35000' FROM DUAL
UNION ALL SELECT 3000, 254, 5, 'PARIS' FROM DUAL
UNION ALL SELECT 3001, 401, 5, 'LONDON' FROM DUAL
UNION ALL SELECT 3002, 405, 5, 'SYDNEY' FROM DUAL
UNION ALL SELECT 4000, 406, 6, 'x' FROM DUAL;
CREATE TABLE OID (OIDID, OID, DESCRIPTION ) AS
SELECT 1, 'x', 'x' FROM DUAL
UNION ALL SELECT 2, 'x', 'x' FROM DUAL
UNION ALL SELECT 3, 'x', 'x' FROM DUAL
UNION ALL SELECT 4, '1.3.6.1.4.1', 'Post Code' FROM DUAL
UNION ALL SELECT 5, '1.3.6.1.4.2', 'City' FROM DUAL
UNION ALL SELECT 6, 'x', 'x' FROM DUAL
UNION ALL SELECT 7, 'x', 'x' FROM DUAL
UNION ALL SELECT 8, 'x', 'x' FROM DUAL
UNION ALL SELECT 9, 'x', 'x' FROM DUAL
UNION ALL SELECT 10, 'x', 'x' FROM DUAL;
查询 1:
SELECT LBKEY,
MAX( CASE OIDID WHEN 4 THEN VALUE END ) AS "Post Code",
MAX( CASE OIDID WHEN 5 THEN VALUE END ) AS "City"
FROM ACCOUNT a
INNER JOIN
CrossReference c
ON ( a.ACCOUNTID = c.ACCOUNTID )
WHERE c.OIDID IN ( 4, 5 )
GROUP BY LBKEY
结果:
| LBKEY | POST CODE | CITY |
|----------|-----------|--------|
| value254 | (null) | PARIS |
| value405 | 35000 | SYDNEY |
| value401 | 40000 | LONDON |
查询 2:
WITH data AS (
SELECT LBKEY,
( SELECT VALUE
FROM CrossReference c
WHERE c.ACCOUNTID = a.ACCOUNTID
AND c.OIDID = 4 ) AS "Post Code",
( SELECT VALUE
FROM CrossReference c
WHERE c.ACCOUNTID = a.ACCOUNTID
AND c.OIDID = 5 ) AS "City"
FROM ACCOUNT a
)
SELECT *
FROM data
WHERE "Post Code" IS NOT NULL
OR "City" IS NOT NULL
结果:
| LBKEY | POST CODE | CITY |
|----------|-----------|--------|
| value254 | (null) | PARIS |
| value401 | 40000 | LONDON |
| value405 | 35000 | SYDNEY |
查询 3:
SELECT LBKEY,
c1.VALUE AS "Post Code",
c2.VALUE AS City
FROM ACCOUNT a
LEFT OUTER JOIN
( SELECT ACCOUNTID, VALUE FROM CrossReference WHERE OIDID = 4 ) c1
ON ( c1.ACCOUNTID = a.ACCOUNTID )
LEFT OUTER JOIN
( SELECT ACCOUNTID, VALUE FROM CrossReference WHERE OIDID = 5 ) c2
ON ( c2.ACCOUNTID = a.ACCOUNTID )
WHERE c1.VALUE IS NOT NULL
OR c2.VALUE IS NOT NULL
结果:
| LBKEY | POST CODE | CITY |
|----------|-----------|--------|
| value254 | (null) | PARIS |
| value401 | 40000 | LONDON |
| value405 | 35000 | SYDNEY |