简体   繁体   English

Oracle 10g中的Pivot / Crosstab查询(动态列号)

[英]Pivot / Crosstab Query in Oracle 10g (Dynamic column number)

I have this table view 我有这个表视图

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

How can I create a query that will provide this pivot view in Oracle 10g ? 如何在Oracle 10g中创建将提供此数据透视视图的查询?

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

Any way to do it dynamically? 有没有办法动态地做到这一点? I saw so many approaches (decode, PL/SQL loops, unions, 11g pivot) 我看到了很多方法(解码,PL / SQL循环,工会,11g枢轴)

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 is the first to support PIVOT/UNPIVOT, so you have to use: Oracle 11g是第一个支持PIVOT / UNPIVOT的,所以你必须使用:

  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

You could use DECODE, but CASE has been supported since 9i. 您可以使用DECODE,但自9i以来一直支持CASE。

I guess one would have to write some code to dynamically create the query. 我想有人必须编写一些代码来动态创建查询。 Each MAX() line is identical except for the 'CHAIR', 'TABLE', etc, strings. 每个MAX()行都是相同的,除了'CHAIR','TABLE'等字符串。

So, one would have to itterate through the data to find all the products and build up a second query as one goes. 因此,人们将不得不通过数据来查找所有产品并构建第二个查询。 Then execute that dynamically built query. 然后执行该动态构建的查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM