Pivot Oracle中的关键词

时间:2011-12-16 07:13:21

标签: sql oracle

我是否可以使用Oracle中的PIVOT关键字为单行创建多列,方法是使用单个查询而不是如下所示的两个查询。 例如..

1)

SELECT
  * 
 FROM 
(
SELECT elig.person_id,elig.cmpo_key, recm.pyin_amt FROM sp_cmpo_elig elig, sp_base_pay_recm recm 
  WHERE elig.cmpo_elig_key=recm.cmpo_elig_key AND elig.person_id='807114' ) temp
pivot (Max(temp.pyin_amt) FOR (cmpo_key) IN (1 AS pyin_amt_1, 2 AS pyin_amt_2, 3 AS pyin_amt_3, 4 AS pyin_amt_4 ))

如果我使用此查询,我将得到如下的输出..

PERSON_ID   PYIN_AMT_1   PYIN_AMT_2  PYIN_AMT_3   PYIN_AMT_4
807114       1524.23        235.25   235.25        235.25

2)

SELECT
  * 
 FROM 
(
SELECT elig.person_id,elig.cmpo_key, recm.pyin_pct FROM sp_cmpo_elig elig, sp_base_pay_recm recm 
  WHERE elig.cmpo_elig_key=recm.cmpo_elig_key AND elig.person_id='807114' ) temp
pivot (Max(temp.pyin_pct) FOR (cmpo_key) IN (1 AS pyin_pct_1, 2 AS pyin_pct_2, 3 AS pyin_pct_3, 4 AS pyin_pct_4 ))

输出:

PERSON_ID   PYIN_PCT_1   PYIN_PCT_2  PYIN_PCT_3   PYIN_PCT_4
807114       2             5          5            3

我可以创建单个查询而不是上面的两个查询。请为此提供解决方案。

注意:我也尝试使用union,如果我使用union,它会给出两个记录,如下面的......

PERSON_ID   PYIN_AMT_1   PYIN_AMT_2  PYIN_AMT_3   PYIN_AMT_4
807114       1524.23        235.25   235.25        235.25
807114       2              5        5             3

我的预期输出不像上面那样,我期待如下......

PERSON_ID   PYIN_AMT_1   PYIN_AMT_2  PYIN_AMT_3   PYIN_AMT_4 PYIN_PCT_1   PYIN_PCT_2  PYIN_PCT_3   PYIN_PCT_4
807114       1524.23        235.25   235.25        235.25        2              5        5             3

2 个答案:

答案 0 :(得分:0)

SELECT
  * 
 FROM 
(
SELECT elig.person_id,elig.cmpo_key, recm.pyin_amt FROM sp_cmpo_elig elig, sp_base_pay_recm recm 
  WHERE elig.cmpo_elig_key=recm.cmpo_elig_key AND elig.person_id='807114' ) temp
pivot (Max(temp.pyin_amt) FOR (cmpo_key) IN (1 AS pyin_amt_1, 2 AS pyin_amt_2, 3 AS pyin_amt_3, 4 AS pyin_amt_4 ))
UNION
SELECT
  * 
 FROM 
(
SELECT elig.person_id,elig.cmpo_key, recm.pyin_pct FROM sp_cmpo_elig elig, sp_base_pay_recm recm 
  WHERE elig.cmpo_elig_key=recm.cmpo_elig_key AND elig.person_id='807114' ) temp
pivot (Max(temp.pyin_pct) FOR (cmpo_key) IN (1 AS pyin_pct_1, 2 AS pyin_pct_2, 3 AS pyin_pct_3, 4 AS pyin_pct_4 ))

答案 1 :(得分:0)

您可以在pivot子句中指定多个聚合

SELECT
  * 
 FROM 
(
SELECT elig.person_id,elig.cmpo_key, recm.pyin_amt FROM sp_cmpo_elig elig, sp_base_pay_recm recm 
  WHERE elig.cmpo_elig_key=recm.cmpo_elig_key AND elig.person_id='807114' ) temp
pivot (Max(temp.pyin_amt) AMT ,Max(temp.pyin_pct) PCT FOR (cmpo_key) IN (1 AS pyin_1, 2 AS pyin_2, 3 AS pyin_3, 4 AS pyin_4 ))

你可以看到我添加了两个MAX子句并给它们别名。我还重命名IN子句中的别名以删除聚合列名称

如果你使用它,你应该使用名为pyin_1_amtpyin_1_pct等的列...

另请参阅Oracle Pivot query gives columns with quotes around the column names. What?,其中包含测试数据的完整可行答案。