求助一个sql的写法

aoxianglin 2010-07-13 03:51:21
表t
id type(类别) num
0001 1 10
0001 2 33

我想要查询后的结果是
id 类别1 类别2
0001 10 30

这样的sql要怎么写?
...全文
99 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
行舟 2010-07-13
  • 打赏
  • 举报
回复
又一个行列转换的问题。。。
mahanso 2010-07-13
  • 打赏
  • 举报
回复
--create table
create table test4
(
id varchar2(4),
type number,
num number,
other1 varchar2(20),
other2 varchar2(20)
)



--insert data
declare
begin
for i in 1 .. 100 loop
insert into test4
select '000'||trunc(dbms_random.value(1,9)),trunc(dbms_random.value(1,9)),trunc(dbms_random.value(1,100)),dbms_random.string('m',5),dbms_random.string('x',5) from dual;
end loop;
commit;
end;

--查询是否有重复数据
select * from test4 a
where rowid > (select min(rowid) from test4 b where a.id = b.id and a.type=b.type)


--select

select id,
max(decode(type,1,num,0)) as 类别1,
max(decode(type,2,num,0)) as 类别2,
max(decode(type,3,num,0)) as 类别3,
max(decode(type,4,num,0)) as 类别4,
max(decode(type,5,num,0)) as 类别5,
max(decode(type,6,num,0)) as 类别6,
max(decode(type,7,num,0)) as 类别7,
max(decode(type,7,num,0)) as 类别8,
max(decode(type,9,num,0)) as 类别9,
other1,
other2
from test4
group by id,other1,other2


drop table test4
mahanso 2010-07-13
  • 打赏
  • 举报
回复
如果id 和 type重复情况下,你想输出什么结果呢?
tangren 2010-07-13
  • 打赏
  • 举报
回复
加上其它可以聚合的字段,然后group by
如果type不定,可以使用存储过程来动态拼接类似的SQL
iqlife 2010-07-13
  • 打赏
  • 举报
回复
怎么会少了?你试过了?你是按ID,将行转为列,当然得分组了...
baobeizhu100 2010-07-13
  • 打赏
  • 举报
回复
进来学习
aoxianglin 2010-07-13
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 java3344520 的回复:]
类别无限制(指很多)?
有限制例如总共5个
有限制可以使用

SQL code
select id,
max(decode(type,'1',num,0)) as 类别1,
max(decode(type,'2',num,0)) as 类别2
......
from t
group by id
[/Quote]

类别是有限制的,但是这个不能分组
这个表id+type不能确定唯一值还有加上其他属性才能确定唯一值的
分组了,那数据不就少了
iqlife 2010-07-13
  • 打赏
  • 举报
回复
类别无限制(指很多)?
有限制例如总共5个
有限制可以使用
select id,
max(decode(type,'1',num,0)) as 类别1,
max(decode(type,'2',num,0)) as 类别2
......
from t
group by id

aoxianglin 2010-07-13
  • 打赏
  • 举报
回复
select id,
decode(type,'1',num),
decode(type,'2',num)
from t
这样可以么
如果该表还有其他属性
id+type不能确定唯一值的呢?

17,377

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧