一个SQL求和的问题

c_cwh 2011-05-13 11:57:46
原始表
ID QTY
001 20
002 20
003 35
003 5
004 10
004 1

希望的结果
ID QTY 新列
001 20 20
002 20 20
003 35
003 5 40
004 10
004 1 11
请教高手,这个SQL语句怎么写?
...全文
45 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
叶子 2011-05-13
  • 打赏
  • 举报
回复

declare @table table (ID varchar(3),QTY int)
insert into @table
select '001',20 union all
select '002',20 union all
select '003',35 union all
select '003',5 union all
select '004',10 union all
select '004',1

select t.*,新列=case when row_number() over (partition by t.ID order by t.ID )<>1
and m.ID is not null then ''
else cast((select sum(QTY) from @table where ID=t.ID) as varchar(10)) end
from @table t left join (select ID from @table group by ID having(count(*)>1)) m
on t.ID=m.ID order by m.ID,QTY

/*
ID QTY 新列
---- ----------- ----------
001 20 20
002 20 20
003 5
003 35 40
004 1
004 10 11
*/

yibey 2011-05-13
  • 打赏
  • 举报
回复

create table #tb(num int identity(1,1) ,ID varchar(20), QTY int)
insert into #tb
select
'001', '20'
union
select
'002', '20'
union
select
'003', '35'
union
select
'003', '5'
union
select
'004', '10'
union
select
'004', '1'


select a.*,(case when a.num =(select max(num) from #tb where id = a.id) then b.xinlie else null end) as xinlie
from #tb a left join
(select id,sum(QTY)as xinlie from #tb group by id) b
on a.id = b.id


ForFumm 2011-05-13
  • 打赏
  • 举报
回复
没有规则?

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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