0

我有两个看起来像这样的表:

LOAN_APP_QST (profile on lending) and
QST_PART (it set up all the fields of loan application).

询问:

SELECT LOAN_APP_QST.REQ_ID,
       LOAN_APP_QST.QST_PART_ID,
       LOAN_APP_QST.LAQ_VALUE,
       QST_PART.QP_NUM,
       QST_PART.QP_NAME
  FROM    SP_MTS.LOAN_APP_QST LOAN_APP_QST
       INNER JOIN
          SP_MTS.QST_PART QST_PART
       ON (LOAN_APP_QST.QST_PART_ID = QST_PART.QST_PART_ID)
       WHERE LOAN_APP_QST.REQ_ID = 23000; 

查询结果:

REQ_ID     QST_PART_ID     LAQ_VALUE     QP_NUM      QP_NAME
23000          -1           IVANOV       surname    FirstName
23000          -2           IVAN          name      LastName
23000          -3           V.            pname     Patronymic

我想要这样的输出:

REQ_ID      surname     name    pname
23000       IVANOV       IVAN   V.

我正在使用 Oracle DB 11。如何实现?

4

1 回答 1

1

在 Oracle 11g 中,您可以使用以下PIVOT功能:

select *
from
(
  SELECT LOAN_APP_QST.REQ_ID,
   LOAN_APP_QST.LAQ_VALUE,
   QST_PART.QP_NUM
  FROM SP_MTS.LOAN_APP_QST LOAN_APP_QST
  INNER JOIN SP_MTS.QST_PART QST_PART
    ON (LOAN_APP_QST.QST_PART_ID = QST_PART.QST_PART_ID)
  WHERE LOAN_APP_QST.REQ_ID = 23000
) src
pivot
(
  max(LAQ_VALUE)
  for QP_NUM in (surname, name, pname)
) piv;

这也可以使用带有CASE表达式的聚合函数来编写:

SELECT LOAN_APP_QST.REQ_ID,
  max(case when QST_PART.QP_NUM = 'surname' then LOAN_APP_QST.LAQ_VALUE end) as surname,
  max(case when QST_PART.QP_NUM = 'name' then LOAN_APP_QST.LAQ_VALUE end) as name,
  max(case when QST_PART.QP_NUM = 'pname' then LOAN_APP_QST.LAQ_VALUE end) as pname
FROM    SP_MTS.LOAN_APP_QST LOAN_APP_QST
INNER JOIN SP_MTS.QST_PART QST_PART
  ON (LOAN_APP_QST.QST_PART_ID = QST_PART.QST_PART_ID)
WHERE LOAN_APP_QST.REQ_ID = 23000
group by LOAN_APP_QST.REQ_ID; 
于 2013-03-05T12:56:46.587 回答