Oracle数据库:在数据透视表中组合列

时间:2018-05-16 20:20:32

标签: oracle

SQL:

SELECT * FROM
(
  SELECT ORG_TOT_LOWEST_LEVEL_ID, ORG_TOT_ACCTG_DEPT_ID, 
  EMPL_SCENR_DIM_MBR_CD, EMPL_VER_DIM_MBR_CD, ORG_TOT_ALLOC_POOL_CD, 
  EMPL_VAL_AMT, EMPL_FMONTH, EMPL_FYEAR, EMPL_FMONTH
  FROM EMPL_FCST
)
PIVOT
(
  SUM(EMPL_VAL_AMT) 
  FOR (EMPL_FMONTH, EMPL_FYEAR)
  IN ((01,2018), (02,2018))
)

示例数据:

OTHER_SELECT_COLUMNS  |  EMPL_VAL_AMT  |  EMPL_FMONTH  |  EMPL_FYEAR
---------------------   --------------   -------------   ------------
          ABC                 1111             1             2018
          ABC                 1112             6             2019

需要的结果:

OTHER_SELECT_COLUMNS  |  1/2018  |  6/2019
---------------------   ---------  --------   
          ABC             1111       1112      

ERROR:

Error starting at line : 1 in command -
SELECT * FROM
(
  SELECT ORG_TOT_LOWEST_LEVEL_ID, ORG_TOT_ACCTG_DEPT_ID, 
  EMPL_SCENR_DIM_MBR_CD, EMPL_VER_DIM_MBR_CD, ORG_TOT_ALLOC_POOL_CD, 
  EMPL_VAL_AMT, EMPL_FMONTH, EMPL_FYEAR, EMPL_FMONTH
  FROM EMPL_FCST
)
PIVOT
(
 SUM(EMPL_VAL_AMT) 
 FOR (EMPL_FMONTH, EMPL_FYEAR)
 IN ((1,2018), (2,2018))
)
Error at Command Line : 11 Column : 8
Error report -
SQL Error: ORA-00918: column ambiguously defined
00918. 00000 -  "column ambiguously defined"
*Cause:    
*Action:

我正在尝试将EMPL_FMONTHEMPL_FYEAR组合作为我的支点中的FOR,因此列标题在顶部看起来像MM / YYYY,每个列标题下的EMPL_VAL_AMT总和。除了获取查询以将字段组合到FOR之外,我觉得我需要某种EMPL_FMONTH||"/"||EMPL_FYEAR语句。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

列EMPL_FMONTH在select语句中重复。

试试这个。

SELECT * FROM
(
  SELECT ORG_TOT_LOWEST_LEVEL_ID, ORG_TOT_ACCTG_DEPT_ID, 
  EMPL_SCENR_DIM_MBR_CD, EMPL_VER_DIM_MBR_CD, ORG_TOT_ALLOC_POOL_CD, 
  EMPL_VAL_AMT, EMPL_FMONTH, EMPL_FYEAR
  FROM EMPL_FCST
)
PIVOT
(
 SUM(EMPL_VAL_AMT) 
 FOR (EMPL_FMONTH, EMPL_FYEAR)
 IN ((1,2018), (2,2018))
)