sql解惑,该怎样写,已写一个感觉不好

dabster1 2008-06-18 02:54:55
有如下表

groupid memberid string val
a 3 stral 6
a 9 stra2 7
b 2 strb1 3
b 4 strb2 7
b 5 strb3 3
b 9 strb4 11
c 3 strc1 8
c 7 strc2 10
c 9 strc3 12
想得出结果如下,注意product,是groupid相对应的val乘积
groupid product
a 42
b 693
c 960

谢谢
...全文
154 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
lff642 2008-07-07
  • 打赏
  • 举报
回复
2楼和7楼的算法都是一样的。
lff642 2008-07-07
  • 打赏
  • 举报
回复
写个函数比较方便,因为你的返回值,只是一个值而以。
SQLnewlearner 2008-07-07
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 victory610 的回复:]
楼主写的好极了,学习了。
[/Quote]
gkl0818 2008-07-07
  • 打赏
  • 举报
回复
学习了~~~`
victory610 2008-07-06
  • 打赏
  • 举报
回复
楼主写的好极了,学习了。
zhiguo2008 2008-07-06
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 liangCK 的回复:]
写函数..
[/Quote]

也可以这样子
if object_id('tempdb.dbo.T') is not null drop table T
create table T (groupid varchar(1),memberid int,string varchar(5),val int)
insert into T
select 'a',3,'stral',6 union all
select 'a',9,'stra2',7 union all
select 'b',2,'strb1',3 union all
select 'b',4,'strb2',7 union all
select 'b',5,'strb3',3 union all
select 'b',9,'strb4',11 union all
select 'c',3,'strc1',8 union all
select 'c',7,'strc2',10 union all
select 'c',9,'strc3',12
go
create function dbo.f_total(@groupid varchar(1))
returns bigint
as
begin
declare @re bigint
set @re=1

select @re=@re*val
from T
where groupid=@groupid
return @re
end
select distinct groupid,dbo.f_total(groupid) total
from T


cjjsun 2008-07-06
  • 打赏
  • 举报
回复
顶!
hery2002 2008-07-06
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 liangCK 的回复:]
写函数..
[/Quote]
如2楼.
yyixin 2008-07-06
  • 打赏
  • 举报
回复
标记
czvos 2008-07-06
  • 打赏
  • 举报
回复
收藏先
liangCK 2008-06-18
  • 打赏
  • 举报
回复
--> 测试数据: #T
if object_id('tempdb.dbo.T') is not null drop table T
create table T (groupid varchar(1),memberid int,string varchar(5),val int)
insert into T
select 'a',3,'stral',6 union all
select 'a',9,'stra2',7 union all
select 'b',2,'strb1',3 union all
select 'b',4,'strb2',7 union all
select 'b',5,'strb3',3 union all
select 'b',9,'strb4',11 union all
select 'c',3,'strc1',8 union all
select 'c',7,'strc2',10 union all
select 'c',9,'strc3',12
go
create function dbo.f_total(@groupid varchar(1))
returns bigint
as
begin
declare @re bigint
set @re=1

select @re=@re*val
from T
where groupid=@groupid
return @re
end

go
select groupid,dbo.f_total(groupid) total
from T
group by groupid

drop table T
drop function dbo.f_total

/*
groupid total
------- --------------------
a 42
b 693
c 960

(3 行受影响)
*/
liangCK 2008-06-18
  • 打赏
  • 举报
回复
写函数..

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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