如何在数据透视中应用条件聚合函数?

时间:2018-01-23 15:44:44

标签: sql oracle oracle11g

我有以下查询:

SELECT "CASE_RECORD_ID",
  "OPEN_DT",
  "PENDING_DT",
  "CLOSED_DT"
FROM
  (SELECT case_record_id,
    workflow_status_cd,
    workflow_status_dt
  FROM case_workflow_status
  ) PIVOT ( MIN(workflow_status_dt) FOR workflow_status_cd IN ('O' AS open_dt, 'P' AS pending_dt, 'C' AS closed_dt) );

我如何应用不同的聚合函数,具体取决于workflow_status_cd是什么?我的非工作尝试如下:

SELECT "CASE_RECORD_ID",
    "OPEN_DT",
    "PENDING_DT",
    "CLOSED_DT"
  FROM
    (SELECT case_record_id,
      workflow_status_cd,
      workflow_status_dt
    FROM case_workflow_status
    ) 

    PIVOT (

    (
    CASE workflow_status_cd
        WHEN 'O' THEN MIN(workflow_status_dt)
        WHEN 'P' THEN MAX(workflow_status_dt)
        WHEN 'C' THEN MAX(workflow_status_dt)
    END
    )
      FOR workflow_status_cd IN ('O' AS open_dt, 'P' AS pending_dt, 'C' AS closed_dt) 
  );

1 个答案:

答案 0 :(得分:3)

只需使用适当的聚合函数,并在每个函数中使用CASE语句来匹配相应的状态:

SELECT CASE_RECORD_ID,
       MIN( CASE WHEN workflow_status_cd = 'O' THEN workflow_status_dt END ) AS OPEN_DT,
       MAX( CASE WHEN workflow_status_cd = 'P' THEN workflow_status_dt END ) AS PENDING_DT,
       MAX( CASE WHEN workflow_status_cd = 'C' THEN workflow_status_dt END ) AS CLOSED_DT
FROM   case_workflow_status
GROUP BY CASE_RECORD_ID;