oracle怎样实现下面这种数据库表的变换,去除多个列的重复值?
日期名称种类金额1acg1acg1ad1be1be1be-----------变成下面这样-------------日期名称种类金额1acg1bd1e...
日期 名称 种类 金额
1 a c g
1 a c g
1 a d
1 b e
1 b e
1 b e
-----------变成下面这样-------------
日期 名称 种类 金额
1 a c g
1 b d
1 e 展开
1 a c g
1 a c g
1 a d
1 b e
1 b e
1 b e
-----------变成下面这样-------------
日期 名称 种类 金额
1 a c g
1 b d
1 e 展开
1个回答
展开全部
单纯是你这样的数据倒是好弄,但你实际不是这样的数据吧。
创建表和插入数据
create table t
(日期 int,
名称 varchar2(10),
种类 varchar2(10),
金额 varchar2(10));
insert into t values (1,'a','c','g');
insert into t values (1,'a','c','g');
insert into t values (1,'a','d',null);
insert into t values (1,'b','e',null);
insert into t values (1,'b','e',null);
insert into t values (1,'b','e',null);
执行:
with t0 as
(select rownum rn from dual connect by rownum<=
(select max(count1) from
(select count(distinct 日期) count1 from t
union all
select count(distinct 名称) from t
union all
select count(distinct 种类) from t
union all
select count(distinct 金额) from t) s))
select t1.日期,t2.名称,t3.种类,t4.金额 from t0,
(select row_number() over (order by 日期) rn,日期 from t group by 日期) t1,
(select row_number() over (order by 名称) rn,名称 from t group by 名称) t2,
(select row_number() over (order by 种类) rn,种类 from t group by 种类) t3,
(select row_number() over (order by 金额) rn,金额 from t group by 金额) t4
where t0.rn=t1.rn(+)
and t0.rn=t2.rn(+)
and t0.rn=t3.rn(+)
and t0.rn=t4.rn(+)
结果:
追问
有没有更简单一点的方法?因为的实际的表的数据是有很多列的,有24列
追答
with t0 as
(select rownum rn from dual connect by rownum<=
(select max(count1) from
(select count(distinct 日期) count1 from t
union all
select count(distinct 名称) from t
union all
select count(distinct 种类) from t
union all
select count(distinct 金额) from t) s))
select t1.日期,t2.名称,t3.种类,t4.金额 from t0,
(select distinct 日期 from t) t1,
(select row_number() over (order by 名称) rn,名称 from t group by 名称) t2,
(select row_number() over (order by 种类) rn,种类 from t group by 种类) t3,
(select row_number() over (order by 金额) rn,金额 from t group by 金额) t4
where t0.rn=t2.rn(+)
and t0.rn=t3.rn(+)
and t0.rn=t4.rn(+)
结果:
目前,觉得你这些数据不够典型,因为日期只有一个值,24个列也没办法,没什么太好办法,你这个查询复杂倒是不复杂,但是你最后要求的结果的格式很讨厌
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询