在 Oracle 中使用聚合旋转/透视表

Rotate/pivot table with aggregation in Oracle(在 Oracle 中使用聚合旋转/透视表)
本文介绍了在 Oracle 中使用聚合旋转/透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Oracle 11g 中旋转一个表.枢轴选项需要聚合.这是我的原始表格:

I'd like to rotate a table in Oracle 11g. The pivot option requires an aggregation. This is my original table:

project | attribute | value
===========================
'cust1' | 'foo'     | '4'
'cust2' | 'bar'     | 'tbd'
'cust3  | 'baz'     | '2012-06-07'
'cust1' | 'bar'     | 'tdsa'
'cust4' | 'foo'     | '22'
'cust4' | 'baz'     | '2013-01-01'

旋转后,表格应如下所示:

After pivoting, the table should look like this:

project | foo | bar | baz
=========================
'cust1' | '4' |'tdba'| NULL
'cust2' | NULL|'tbd' | NULL
'cust3' | NULL| NULL | '2012-06-07'
'cust4' | '22'| NULL | '2013-01-01'

现在,如您所见,分组应该发生在项目列上.不需要折叠或计算任何值.只需轮换一次.那么,枢轴选择是否正确?

Now, as you can see, the grouping should happen over the project column. No values need to be collapsed or calcucation. A mere rotation is necessary. So, is the pivot select the right thing to do?

推荐答案

是的,我想是的.使用 MAX 聚合很容易进行这样的数据透视:

Yes I think so. It is easy to do a pivot like this with a MAX aggregate:

SELECT
    *
FROM
(
    SELECT
        project,
        attribute,
        value
    FROM
        table1
) AS SourceTable
PIVOT
(
    MAX(value)
    FOR attribute IN ([foo],[bar],[baz])
) AS pvt

否则,您必须在 a max 聚合中执行 case 语句.像这样:

Otherwise you have to do a case statement inside the a max aggregate. Like this:

SELECT
    MAX(CASE WHEN attribute='foo' THEN value ELSE NULL END) AS foo,
    MAX(CASE WHEN attribute='bar' THEN value ELSE NULL END) AS bar,
    MAX(CASE WHEN attribute='baz' THEN value ELSE NULL END) AS baz,
    project
FROM
    table1
GROUP BY
    project

这与执行 PIVOT 几乎相同.但我更喜欢 PIVOT 而不是 CASE WHEN MAX..

This is almost the same thing as doing the PIVOT. But I would prefer doing the PIVOT over the CASE WHEN MAX..

这篇关于在 Oracle 中使用聚合旋转/透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)