34,593
社区成员
发帖
与我相关
我的任务
分享
--amount如果有小数必须先转换
declare @t table(ID int,amount nvarchar(10))
insert @t select 1,'12.3'
insert @t select 1,'12'
insert @t select 2,'1.0'
select ID,
sum(cast(amount as dec(18,2)))amount
from @t
where isnumeric(amount)=1
group by ID
select id,sum(convert(amount as int)) as amount_sum
from table
group by id
if object_id('#') is not null drop table #
create table #(ID int, amount varchar(8))
insert into #
select 1, 'F' union all
select 2, 'E' union all
select 2, 'D' union all
select 3, 'C' union all
select 3, 'B' union all
select 3, 'A'
go
select ID, amount = stuff((select ',' + amount from # where ID = t.ID for xml path('')) , 1, 1, '') from # as t group by ID
go
/*
ID amount
---- --------
1 F
2 E,D
3 C,B,A
*/
select ID,
sum(amount)amount
from tb
where isnumeric(amount)=1
group by id