SQL Oracle-将行转换为列

时间:2018-08-09 15:42:24

标签: sql oracle

我的SQL输出当前产生以下结果:

DEPARTMENT | MM-YYYY | ROW_LABEL | SCORE
   A         05-2018    STAFF      79.0
   A         06-2018    STAFF      81.0
   A         05-2018    SCHED      72.3
   A         06-2018    SCHED      74.5
   B         05-2018    STAFF      77.4
   B         06-2018    STAFF      74.3
   B         05-2018    SCHED      81.3
   B         06-2018    SCHED      78.6

我的目标是自动将行中的日期值转换为它自己的列。像这样:

DEPARTMENT | ROW_LABEL | 05-2018 | 06-2018
   A           STAFF      79.0      81.0
   A           SCHED      72.3      74.5
   B           STAFF      77.4      74.3
   B           SCHED      81.3      78.6 

该报告每月更改一次,因此目标是自动填充MM-YYYY +得分。下次我运行该报表时,它将是06-2018和07-2018,我不想每次生成此报告时都要对日期进行硬编码。

1 个答案:

答案 0 :(得分:0)

您可以尝试这样:

SQL DEMO

SELECT 
     "DEPARTMENT", "ROW_LABEL" ,
     MAX(CASE WHEN "MMYYYY" = (select TO_CHAR(ADD_MONTHS(sysdate,-1), 'MM-YYYY') from dual)
              THEN "SCORE"
         END) as previous_month,
     MAX(CASE WHEN "MMYYYY" = (select TO_CHAR(sysdate, 'MM-YYYY') from dual)
              THEN "SCORE"
         END) as current_month           
FROM Table1
GROUP BY "DEPARTMENT", "ROW_LABEL" 
ORDER BY "DEPARTMENT", "ROW_LABEL" DESC;

输出

| DEPARTMENT | ROW_LABEL | PREVIOUS_MONTH | CURRENT_MONTH |
|------------|-----------|----------------|---------------|
|          A |     STAFF |             79 |            81 |
|          A |     SCHED |           72.3 |          74.5 |
|          B |     STAFF |           77.4 |          74.3 |
|          B |     SCHED |           81.3 |          78.6 |

如果您想在标题上输入确切的日期,则需要DYNAMIC PIVOT