首页 > 解决方案 > 聚合函数选择

问题描述

有一个 tbl_Regist 表:

| ID | CODE   | VAL       |
+----+--------+-----------+
| 95 | numVz  | 06        |
| 95 | prevVz | 84605898  |
| 95 | ndatVz | 10.10.10  |
| 95 | numVz  | 06        |
| 95 | prevVz | 14666641  |
| 95 | ndatVz | 11.11.11  |
| 95 | numVz  | 06        |
| 95 | prevVz | 84605898  |
| 95 | ndatVz | 12.12.12  |  

我需要在这个视图中获取数据:

| ID | numVz | prevVz   | ndatVz   | 
+----|-------+----------+----------+
| 95 | 06    | 84605898 | 10.10.10 |   
| 95 | 06    | 14666641 | 11.11.11 |
| 95 | 06    | 84605898 | 12.12.12 |    

我的请求:

select 
      t.ID,
      max(case when t.code = 'numVz'  then t.val end) as numVz
     ,max(case when t.code = 'prevVz' then t.val end) as prevVz
     ,max(case when t.code = 'ndatVz' then t.val end) as ndatVz
from tbl_Regist t
where t.ID = 95
group by t.ID     


| ID | numVz | prevVz   | ndatVz   | 
+----|-------+----------+----------+
| 95 | 06    | 84605898 | 12.12.12 |

只返回一行,如果去掉聚合函数,它返回 9 行

标签: sqloracleplsql

解决方案


您可以使用row_number()来添加枚举。但是,您确实需要一个排序列:

select r.ID,
       max(case when r.code = 'numVz'  then r.val end) as numVz,
       max(case when r.code = 'prevVz' then r.val end) as prevVz,
       max(case when r.code = 'ndatVz' then r.val end) as ndatVz
from (select r.*,
             row_number() over (partition by id, code order by <ordering column>) as seqnum
      from tbl_Regist r
     ) r
where r.ID = 95
group by r.ID, seqnum;

推荐阅读