Sql 如何在Oracle中将行转换为列?
我在Oracle数据库中有一个包含如下所示数据的表Sql 如何在Oracle中将行转换为列?,sql,oracle,oracle10g,pivot,Sql,Oracle,Oracle10g,Pivot,我在Oracle数据库中有一个包含如下所示数据的表 emp_num person_name organization earned_date sum(hours) ------- ----------- ------------ ----------- ---------- 36372 Name1 Test1 23-MAR-11 3.17 36372 Name1 Test1 15-MAR-11
emp_num person_name organization earned_date sum(hours)
------- ----------- ------------ ----------- ----------
36372 Name1 Test1 23-MAR-11 3.17
36372 Name1 Test1 15-MAR-11 6.70
40208 Name2 Test2 08-APR-11 13.50
40208 Name2 Test2 06-APR-11 12.07
我需要更改查询输出,如下所示。我该怎么做
emp_num person_name organization 23-MAR-11 15-MAR-11 08-APR-11 06-APR-11
------- ----------- ------------ --------- --------- --------- ---------
36372 Name1 Test1 3.17 6.70
40208 Name2 Test2 13.50 12.70
始终使用to_date函数将日期与字符串进行比较,我在这里使用了一种常见的英国格式。除非使用某种形式的动态SQL,否则不能动态命名表中的列。但是,您可以使用通用日期列获得所需的内容:
select emp_num, person_name, organization,
sum(decode(datenum, 1, hours, 0)) as date1hours,
sum(decode(datenum, 2, hours, 0)) as date2hours,
...
min(decode(datenum, 1, earned_date) as date1,
min(decode(datenum, 2, earned_date) as date2,
...
from
(
select t.*,
dense_rank() over (partition by NULL order by earned_date) as datenum
from the_table t
) t
group by emp_num, person_name, organization
顺便说一下,Oracle 10g支持
大小写
语法,我建议您不要使用解码
谢谢,我只给出了示例记录。我需要动态列我不知道表数据中的日期是什么。它应该自动将coulmns构建为pe dates可能会有帮助,请您帮助我使用该用例语法我如何可能将我的行按用例转换为列我以前使用过好几次,如select id,如果name不为null,那么name else“N/A”将从表中结束,但我认为它在pivot或transposing中没有用处。@KhurramZulfiqarAli。你不是最初的OP。我建议你问一个特定于你需求的问题。
select emp_num, person_name, organization,
sum(decode(datenum, 1, hours, 0)) as date1hours,
sum(decode(datenum, 2, hours, 0)) as date2hours,
...
min(decode(datenum, 1, earned_date) as date1,
min(decode(datenum, 2, earned_date) as date2,
...
from
(
select t.*,
dense_rank() over (partition by NULL order by earned_date) as datenum
from the_table t
) t
group by emp_num, person_name, organization