先有数据表Table如下:
ID 类型 数量
1 1 1
2 1 2
3 2 3
4 3 4
5 3 5希望得到的结果是:
类型1数量 类型2数量 类型3数量
3 3 9相当于将数据库中多条的数据记录合并为一条记录显示。类型是由常量表CONS中取出的,请教各位前辈这样的SQL语句应该怎么写?小弟不胜感激!
ID 类型 数量
1 1 1
2 1 2
3 2 3
4 3 4
5 3 5希望得到的结果是:
类型1数量 类型2数量 类型3数量
3 3 9相当于将数据库中多条的数据记录合并为一条记录显示。类型是由常量表CONS中取出的,请教各位前辈这样的SQL语句应该怎么写?小弟不胜感激!
create function f_num(@类型 int)
returns int
as
begin
declare @ret int
set @ret = 0
select @ret = @ret + 数量 from Table where 类型=@类型
return @ret
end
go
--执行查询
select dbo.f_str(1) as 类型1数量,dbo.f_str(2) as 类型2数量,dbo.f_str(3) as 类型3数量 from Table
from tab
group by 类型
decode(类型,'1',数量,null) as "类型1数量",
decode(类型,'2',数量,null) as "类型2数量",
decode(类型,'3',数量,null) as "类型3数量"
from
(
select 类型,sum(数量) as 数量from 表
group by 类型
)
re a.lx_id(+)=b.lx_id; LX_ID NVL(A.S_SL,0)
---------- -------------
1 3
2 3
3 9
4 0SQL> select * from t; ID LX_ID SL
---------- ---------- ----------
1 1 1
2 1 2
3 2 3
4 3 4
5 3 5SQL> select * from t1; LX_ID
----------
1
2
3
4SQL>
id number,
lx varchar2(10),
sl number)
/insert into cons select 1,1,1 from dual;
insert into cons select 2,1,2 from dual;
insert into cons select 3,2,3 from dual;
insert into cons select 4,3,4 from dual;
insert into cons select 5,3,5 from dual;
commit;
/SQL> select id ID, lx 类型,sl 数量 from cons; ID 类型 数量
---------- ---------- ----------
1 1 1
2 1 2
3 2 3
4 3 4
5 3 5SQL> select lx 类型,sum(sl) 总数量 from cons group by lx;类型 总数量
---------- ----------
1 3
2 3
3 9