首页 > 解决方案 > 在oracle中将行值添加到列

问题描述

我有一张这样的桌子:

在此处输入图像描述

现在;
我想用 SELECT 语句将行值映射到列。结果应该是这样的:
在此处输入图像描述

标签: sqldatabaseoraclepivot

解决方案


你可以做这样的事情。

Select * from (select id, person_id, f_device, report_date, originaldate)
pivot
(
 count(*)
 for person_id in (1, 2, 3, 4)
);

那就是您需要聚合,您将获得 select 语句和 for 子句中的列。此查询将计算 (1, 2, 3, 4) 中 person_id 的行数,并在内部按剩余列分组。

由于您的问题不清楚,如果不是这种情况,请尝试改进您的问题。

更新

WITH cte as ( select personid id, reportdate c_date, listagg(originaldate||' ') og FROM my_table GROUP BY personid, reportdate),
cte2 as (SELECT  id, c_date, regexp_substr(og, '(.*?)( |$)', 1, 1 ) one,
                                  regexp_substr(og, '(.*?)( |$)', 1, 2) two,
                                  regexp_substr(og, '(.*?)( |$)', 1, 3 ) three,
                                  regexp_substr(og, '(.*?)( |$)', 1, 4 ) four
              from cte)
SELECT * FROM cte2;

如果您希望每行都有一个不同的personid,则需要汇总reportdate

WITH cte as ( select personid id, max(reportdate ) c_date, listagg(originaldate||' ') WITHIN GROUP(ORDER BY personid ) og FROM my_table GROUP BY personid),
cte2 as (SELECT  id, c_date, regexp_substr(og, '(.*?)( |$)', 1, 1 ) one,
                                  regexp_substr(og, '(.*?)( |$)', 1, 2) two,
                                  regexp_substr(og, '(.*?)( |$)', 1, 3 ) three,
                                  regexp_substr(og, '(.*?)( |$)', 1, 4 ) four
              from cte)
SELECT * FROM cte2;

推荐阅读