具有动态数据的Oracle pivot

具有动态数据的Oracle pivot,oracle,dynamic,pivot,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

我是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的映射表

我需要创建一个视图,其中包含表2中的列和每个solname的额外列。因此,视图看起来像

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

有没有办法在oracle数据库中使用PIVOT实现这一点?

对于动态SQL数据透视,您需要执行类似的操作:

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') )
警告:我从未尝试过这一点,但从这里理解了逻辑:

对于静态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') 
);

在xxxx和yyyy列中没有真正定义要存储的内容,可能是1/blank,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"
  )
)

您可以在

上找到更多信息和其他参考。如果要创建视图,则需要在编译时固定视图的定义。因此,如果在
表1
中添加了另一个拖,则无法在视图中动态添加另一列。您可以重新创建视图,甚至可以编写使用动态SQL重新创建视图的存储过程。或者,您可以避免创建视图,并可能执行其他可能是动态的操作——例如,一个返回
SYS\u REFCURSOR
的存储函数,它将是完全动态的。但那样你就看不见了。您更喜欢哪种方法?嗨,Justin,感谢您的快速响应..我认为我的案例重新创建视图是更好的选择…因此,您能告诉我在这种情况下如何使用动态SQL吗
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;