出现问题时的 Oracle 案例

eli*_*erv 1 oracle case

我有一张像休闲的桌子

    work_id      group    effort
   -----------   -----   --------
       1           A        10
       1           B        5
       2           A        7
       2           C        20
       2           B         3
Run Code Online (Sandbox Code Playgroud)

我需要一个查询返回像休耕的情况

   work_id       1.group   effort1   2.Group  effort2    3.group  effort3
   -----------   -----     --------  -------  ------    -------  ------
       1           A        10        B        5
       2           A        7         C        20        B         3
Run Code Online (Sandbox Code Playgroud)

组根据另一个表中的另一个参数进行分组。但是当我写我的查询时

case when <condition1> then group end as 1.group
case when <condition2> then group end as 2.group
case when <condition4> then group end as 3.group
Run Code Online (Sandbox Code Playgroud)

...(努力也是一样)

它返回

work_id       1.group   effort   2.Group  effort    3.group  effort
-----------   -----   --------   -------  ------    -------  ------
    1           A        10        null     null      null     null
    1           null     null     B        5
    2           A        7         null     null    null     null
    2           null     null                          C      20                      
    2           null     null      null      null     B         3
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮忙吗?

Jus*_*ave 6

您正在尝试编写PIVOT查询。如果您尝试使用 aCASE来执行此操作(这意味着您不在 11g 上,您可以简单地使用PIVOT运算符),则需要进行聚合

SELECT work_id,
       MAX( CASE WHEN <<condition1>> then group else null end ) as "1.group",
       MAX( CASE WHEN <<condition2>> then group else null end ) as "2.group",
       MAX( CASE WHEN <<condition3>> then group else null end ) as "3.group",
       MAX( CASE WHEN <<condition1>> then effort else null end ) as "1.effort",
       MAX( CASE WHEN <<condition2>> then effort else null end ) as "2.effort",
       MAX( CASE WHEN <<condition3>> then effort else null end ) as "3.effort"
  FROM <<table name>>
 GROUP BY work_id
Run Code Online (Sandbox Code Playgroud)

当然,您可能实际上没有GROUP在表中命名的列,因为这是一个保留字。