Oracle 10g中的数据透视表/交叉表查询(动态列号) [英] Pivot / Crosstab Query in Oracle 10g (Dynamic column number)

查看:239
本文介绍了Oracle 10g中的数据透视表/交叉表查询(动态列号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此表视图

UserName      Product     NumberPurchaces
--------      -------     ---------------
'John Doe'    'Chair'     4
'John Doe'    'Table'     1
'Jane Doe'    'Table'     2
'Jane Doe'    'Bed'       1

如何创建将在Oracle 10g中提供此透视图视图的查询?

How can I create a query that will provide this pivot view in Oracle 10g ?

 UserName   Chair   Table   Bed
 --------   -----   -----   ---
 John Doe   4       1       0
 Jane Doe   0       2       1

有什么动态方法吗?我看到了很多方法(解码,PL/SQL循环,联合,11g数据透视)

Any way to do it dynamically? I saw so many approaches (decode, PL/SQL loops, unions, 11g pivot)

但是根据上述示例,我还没有找到适合我的东西

But I've yet to find something that will work for me based on the above example

编辑:我不知道开发期间产品的数量或类型,因此必须动态化

Edit: I don't know the number or type of products in development time so this has to be dynamic

推荐答案

Oracle 11g首先支持PIVOT/UNPIVOT,因此必须使用:

Oracle 11g is the first to support PIVOT/UNPIVOT, so you have to use:

  SELECT t.username,
         MAX(CASE WHEN t.product = 'Chair' THEN t.numberpurchases ELSE NULL END) AS chair,
         MAX(CASE WHEN t.product = 'Table' THEN t.numberpurchases ELSE NULL END) AS tbl,
         MAX(CASE WHEN t.product = 'Bed' THEN t.numberpurchases ELSE NULL END) AS bed
    FROM TABLE t
GROUP BY t.username

您可以使用DECODE,但是从9i开始就支持CASE.

You could use DECODE, but CASE has been supported since 9i.

这篇关于Oracle 10g中的数据透视表/交叉表查询(动态列号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆