问SQL语句
字段a 字段b 字段c
a1 10 5
a2 20 20
a3 20 20
a4 20 20
a1 10 5
a5 20 20
SQL语句的结果
字段a 字段b 字段c
a1 10 5
a2 20 20
a3 20 20
a4 20 20
a1 10 3
a5 20 20
合计 90 88
(说明合计时:当字段a的值相同时(a1),合计字段b只计算第一个值(不算第2个10),合计字段c全算)
------解决方案--------------------declare @t table(字段a varchar(8),字段b int,字段c int)
insert into @t select 'a1 ',10,5
insert into @t select 'a2 ',20,20
insert into @t select 'a3 ',20,20
insert into @t select 'a4 ',20,20
insert into @t select 'a1 ',10,5
insert into @t select 'a5 ',20,20
select * from @t
union all
select '合计 ',sum(字段b),sum(字段c) from @t
/*
字段a 字段b 字段c
-------- ----------- -----------
a1 10 5
a2 20 20
a3 20 20
a4 20 20
a1 10 5
a5 20 20
合计 100 90
*/
------解决方案--------------------子陌,你上面的字段b没有去掉a1重复的...
------解决方案--------------------沒有關鍵字,借用下臨時表
declare @t table(字段a varchar(8),字段b int,字段c int)
insert into @t select 'a1 ',10,5
insert into @t select 'a2 ',20,20
insert into @t select 'a3 ',20,20
insert into @t select 'a4 ',20,20
insert into @t select 'a1 ',10,5
insert into @t select 'a5 ',20,20
select ID = Identity(Int, 1, 1), * Into #T from @t
select * from @t
union all
select N '合计 ', sum(字段b), sum(字段c) from (
select (Case When Exists (Select ID From #T Where 字段a = A.字段a And ID < A.ID) Then 0 Else 字段b End) As 字段b, (字段c) from #T A) B
Drop Table #T
/*
字段a 字段b 字段c
-------- ----------- -----------
a1 10 5
a2 20 20
a3 20 20
a4 20 20
a1 10 5
a5 20 20
合计 90 90
*/