oracle 将一组值通过透视表或矩阵按组转换为一行

nwlls2ji  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(99)

我有点困惑,因为我熟悉pivot-我正在寻找一种方式来获取已经聚合的值,并根据ID和药物类型将它们放入一行-例如:T0是第一天的总剂量,T5是第5天的总剂量,Total_dose是所有天数的总剂量
输入:

with samp as (select 1 as ID, 'A' as medication, 6 as T0, 8 as T5, 35 as total_dose from dual union all
         select 1 as ID, 'B' as medication, 3 as T0, 2 as T5, 15 as total_dose from dual union all
         select 2 as ID, 'A' as medication, 6 as T0, NULL as T5, 18 as total_dose from dual union all
         select 2 as ID, 'C' as medication, 100 as T0, 120 as T5, 550 as total_dose from dual)
         
select * from samp;

它是什么
| ID|药物|t0| T5|总剂量|
| - -|- -|- -|- -|- -|
| 1|一|6| 8| 35|
| 1| B| 3| 2| 15|
| 2|一|6||18|
| 2| C| 100| 120| 550|
我想要的是:
| ID| T0_A| T5_A|总剂量A| T0_B| T5_B|总剂量_B| T0_C| T5_C|总剂量C|
| - -|- -|- -|- -|- -|- -|- -|- -|- -|- -|
| 1| 6| 8| 35| 3| 2| 15||||
| 2| 6||18||||100| 120| 550|
我需要动态地做这件事,因为可能有大约100种药物。任何帮助感激不尽。

70gysomp

70gysomp1#

您可以用途:

WITH samp (id, medication, T0, T5, total_dose) AS (
  SELECT 1, 'A',   6,    8,  35 FROM DUAL UNION ALL
  SELECT 1, 'B',   3,    2,  15 FROM DUAL UNION ALL
  SELECT 2, 'A',   6, NULL,  85 FROM DUAL UNION ALL
  SELECT 2, 'C', 100,  120, 550 FROM DUAL
)
SELECT id,
       a_t0 AS t0_a,
       a_t5 AS t5_a,
       a_total_dose AS total_dose_a,
       b_t0 AS t0_b,
       b_t5 AS t5_b,
       b_total_dose AS total_dose_b,
       c_t0 AS t0_c,
       c_t5 AS t5_c,
       c_total_dose AS total_dose_c
FROM   samp
PIVOT (
  MAX(T0) AS t0,
  MAX(T5) AS t5,
  MAX(Total_Dose) AS total_dose
  FOR medication IN (
    'A' AS a,
    'B' AS b,
    'C' AS c
  )
);

其输出:
| ID| T0_A| T5_A|总剂量A| T0_B| T5_B|总剂量_B| T0_C| T5_C|总剂量C|
| --|--|--|--|--|--|--|--|--|--|
| 1 | 6 | 8 | 35 | 3 | 2 | 15 |* 空 |||
| 2 | 6 |
| 85 ||| 空 *| 100 | 120 | 550 |
如果你想要列为A_T0A_T5A_TOTAL_DOSE等。那么你可以只使用SELECT *而不是重命名列。
fiddle
我需要动态地做这件事,因为可能有大约100种药物。
Oracle本身不支持动态透视表;只需输入所有100个值。
如果你真的想要一个动态透视表,那么你将不得不编写一些PL/SQL代码来生成查询。

相关问题