Oracle数据透视与动态数据

时间:2013-05-20 20:49:59

标签: oracle dynamic pivot

我是oracle数据库的新手,我正在尝试使用PIVOT将行转换为列。我有以下表格..

table 1
solid       solname
--------------
1        xxxxxx
2        yyyyyyy
table2
id      name           abbrv 
----------------------------------
1        test db          tdb
2        Prdocuiton db     pdb

table3
id     solId
-------------
1   1
1   2
1   3
1   4
1   5
1   7
1   8
1   9
1   22
1   23
1   24
1   25
2   26
2   27
1   28
1   29
1   32
1   33
1   34
1   35
1   36
1   37
3   38
1   39
1   40
1   43
1   44

表3是表1和表3的映射表。

我需要创建一个视图,其中包含table2中的列和每个solname的额外列。所以视图看起来像

id      name           abbrv   xxxxxxx    yyyyyyy
--------------------------------------------------

那么有没有办法在oracle数据库中使用PIVOT来做到这一点?

3 个答案:

答案 0 :(得分:3)

对于Dynamic SQL Pivoting,您需要执行类似的操作:

create or replace view sol_view
as
select 
    t1.solname, 
    t2.name, 
    count(t3.abbrv),
from 
    table1 t1, 
    table2 t2, 
    table3 t3
where 
    t1.solid = t3.solid 
    and t2.id = t3.id
group by
    t1.solname,
    t3.name

select * from table( pivot('select * from sol_view') )

警告:我从未尝试过这个,但从这里理解逻辑: http://technology.amis.nl/2006/05/24/dynamic-sql-pivoting-stealing-antons-thunder/

对于静态SQL数据透视,请大致沿着这些方向尝试。从未尝试或测试过:

with pivot_data as (
    select t1.solname, t2.name, t3.abbrv
from table1 t1, table2 t2, table3 t3
where t1.solid = t3.solid 
and t2.id = t3.id
)
select * 
from pivot_data
pivot ( 
    count(abbrv) 
    for solname 
    in ('xxxxxx','yyyyyyy') 
);

答案 1 :(得分:0)

它没有真正定义你要存储在xxxx和yyyy列中的内容,可能是1 /空白,Y / N,......?但是,您的查询可能看起来像这样:

SELECT * FROM (
  SELECT *
  FROM table3 t3
  JOIN table2 t2 USING (id)
  JOIN table1 t1 USING (solid)
) PIVOT (
  COUNT(*) FOR (solname) IN (
    ('xxx') AS "XXX",
    ('yyy') AS "YYY"
  )
)

您可以在My Blog

上找到更多信息和其他参考资料

答案 2 :(得分:-2)

TableName - **tblItem**
Id  ItemName    RecipeName  Quantity
1   Sugar       mutter paneer   200
2   Tea     mutter paneer   100
3   Tomato      mutter paneer   500
4   Onion       mutter paneer   300
5   Ginger      mutter paneer   300
6   Capsicum    mutter paneer   300
7   Sugar       mutter paneer   200
8   Tea     mutter paneer   100
9   Onion       mutter paneer   500
10  Sugar       mutter paneer   200

V_VALUES varchar2(4000);
sql_query varchar2(4000);

SELECT
LISTAGG(''''||ITEMNAME||'''',',')WITHIN GROUP (ORDER BY ITEMNAME)as ITEMNAME
INTO V_LIST
FROM(SELECT DISTINCT ITEMNAME FROM tblItem);

sql_query : = 'SELECT * FROM (
              SELECT ItemName,RecipeName,Sum(Quantity) as Quantity from tblItem group by ItemName,RecipeName)
              PIVOT ( 
        sum(Quantity) for ItemName in (' ||V_LIST|| ') 
        )';

  OPEN p_cursor
     FOR sql_query;