【问题标题】:oracle transposing text value rows to columnsoracle 将文本值行转置为列
【发布时间】:2017-05-04 00:00:30
【问题描述】:

我在 Oracle 中有一个如下设计的表格

+-----------+------+-------+
|    ID     | TYPE | VALUE | 
+-----------+------+-------+
| 1         | A    |     1 |
| 1         | B    |     2 |
| 1         | C    |     3 |
| 2         | A    |     4 |
| 2         | B    |     5 |
| 2         | C    |     6 |
+-----------+------+-------+

我需要像这样转置这个表

    +-----------+------+-------+-----+
    |    ID     | A    |     B |   C | 
    +-----------+------+-------+-----+
    | 1         | 1    |     2 |   3 |
    | 2         | 4    |     5 |   6 |
    +-----------+------+-------+-----+

下面是我使用 oracle pivot 函数将这些行转置为列的 sql。

select * from
(
select ID, TYPE, VALUE from table where TYPE in ('A','B','C')
)
PIVOT (
max(value)
for TYPE in (1 column_a, 2 column_b, 3 column_c)
)

这是我的问题

  1. 这会返回结果,但即使它不为空,也会返回空值。它返回 NULL 是因为我使用的是带有字符串值的聚合函数吗?
  2. 此 SQL 未将值映射到类型。所以基本上值总是需要绑定到类型列。这对 PIVOT 功能可行吗?

我也在考虑通过使用 INSERT 和 SELECT 来重新创建表。请告知使用 PIVOT 是否可行。

【问题讨论】:

  • 你需要 'A','B','C' 而不是 1,2,3

标签: sql oracle pivot


【解决方案1】:

我发现使用条件聚合要容易得多:

select id,
       max(case when type = 'A' then value end) as a,
       max(case when type = 'B' then value end) as b,
       max(case when type = 'C' then value end) as c
from t
group by id;

您可以使用create table as 将结果插入到表中。这也应该适用于数据透视查询。

【讨论】:

  • 我也是;并且它更通用地支持多个数据库平台。
  • @xQbert - 虽然这一切都是真的,但如果一个人真的在 Oracle 中工作并且效率很重要,那么 PIVOT 应该是首选;它比“旧”或“手动”旋转方式占用的 CPU 资源少得多。参见例如guyharrison.squarespace.com/blog/2009/7/27/…
  • 良好的链接和信息。
  • @mathguy 。 . .有趣的。在 SQL Server 上正好相反。
  • 感谢所有 cmets。我尝试了 Pivot,但由于数据集很小,我只是使用这种方式。
【解决方案2】:

枢轴的1,2,3应该是'A','B','C'

with CTE (ID,Type,Value) as (
SELECT 1, 'A',1 from dual union all
SELECT 1, 'B',2 from dual union all
SELECT 1, 'C',3 from dual union all
SELECT 2, 'A',4 from dual union all
SELECT 2, 'B',5 from dual union all
SELECT 2, 'C',6 from dual)

SELECT * 
FROM (SELECT ID, TYPE, VALUE FROM cte WHERE TYPE in ('A','B','C'))  
PIVOT (sum(value)
       for TYPE in ('A' "A",'B' "B",'C' "C"))  --Type has values of A,B,C so you have 
                                               --to pivot on A,B,C.. 1,2,3 are the values.

它返回 NULL 是因为我使用的是带有字符串值的聚合函数吗? 不,因为你的方向错了。以类型为中心而不是类型值

此 SQL 不会将值映射到类型。 *在我看来,只是因为你在做错事...

所以基本上值总是需要绑定到类型列。这对 PIVOT 功能可行吗? 是的,在我看来你只差了 3 个字符

工作示例的 IMG:

【讨论】:

    猜你喜欢
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 2016-11-21
    相关资源
    最近更新 更多