在 Oracle 10g 中,没有PIVOT
函数,但您可以使用聚合复制它CASE
:
select usr,
sum(case when tp ='T1' then cnt else 0 end) T1,
sum(case when tp ='T2' then cnt else 0 end) T2,
sum(case when tp ='T3' then cnt else 0 end) T3
from temp
group by usr;
请参阅带有演示的 SQL Fiddle
如果您有 Oracle 11g+,那么您可以使用以下PIVOT
功能:
select *
from temp
pivot
(
sum(cnt)
for tp in ('T1', 'T2', 'T3')
) piv
请参阅带有演示的 SQL Fiddle
如果您有未知数量的值要转换,那么您可以创建一个过程来生成它的动态版本:
CREATE OR REPLACE procedure dynamic_pivot(p_cursor in out sys_refcursor)
as
sql_query varchar2(1000) := 'select usr ';
begin
for x in (select distinct tp from temp order by 1)
loop
sql_query := sql_query ||
' , sum(case when tp = '''||x.tp||''' then cnt else 0 end) as '||x.tp;
dbms_output.put_line(sql_query);
end loop;
sql_query := sql_query || ' from temp group by usr';
open p_cursor for sql_query;
end;
/
然后执行代码:
variable x refcursor
exec dynamic_pivot(:x)
print x
所有版本的结果都是一样的:
| USR | T1 | T2 | T3 |
----------------------
| 1 | 17 | 0 | 0 |
| 2 | 0 | 21 | 1 |
| 3 | 45 | 0 | 0 |
编辑:根据您的评论,如果您想要一个Total
字段,最简单的方法是将查询放在另一个SELECT
类似于此的内部:
select usr,
T1 + T2 + T3 as Total,
T1,
T2,
T3
from
(
select usr,
sum(case when tp ='T1' then cnt else 0 end) T1,
sum(case when tp ='T2' then cnt else 0 end) T2,
sum(case when tp ='T3' then cnt else 0 end) T3
from temp
group by usr
) src;
请参阅带有演示的 SQL Fiddle