日期:2014-05-18  浏览次数:20675 次

按flag分组,再相加value,但是重复的number只能加一次
表如下:
id number value flag
1 1 10 'A'
2 1 10 'A'
3 1 10 'B'
4 1 10 'C'
5 2 20 'A'
6 3 50 'A'
7 3 50 'A'
8 4 20 'B'
9 5 10 'A'


 按flag分组,再相加value,但是重复的number只能加一次
 结果要输出成这样的
 
 flag flagCount valueSum
 'A' 6 90 
 'B' 2 30
 'C' 1 10

------解决方案--------------------
SQL code
create table tb(id int,number int,value int,flag varchar(10))
insert into tb values(1 ,1 ,10 ,'A')
insert into tb values(2 ,1 ,10 ,'A')
insert into tb values(3 ,1 ,10 ,'B')
insert into tb values(4 ,1 ,10 ,'C')
insert into tb values(5 ,2 ,20 ,'A')
insert into tb values(6 ,3 ,50 ,'A')
insert into tb values(7 ,3 ,50 ,'A')
insert into tb values(8 ,4 ,20 ,'B')
insert into tb values(9 ,5 ,10 ,'A')
go

select flag , 
       (select count(1) from tb where flag = t.flag) flagCount,
       sum(value) valueSum  from
(
  select distinct number , value , flag from tb
) t
group by flag

drop table tb

/*
flag       flagCount   valueSum    
---------- ----------- ----------- 
A          6           90
B          2           30
C          1           10

(所影响的行数为 3 行)
*/

------解决方案--------------------
SQL code

create table sup
(id int, number int, value int, flag char(1))

insert into sup
select 1, 1, 10, 'A' union all
select 2, 1, 10, 'A' union all
select 3, 1, 10, 'B' union all
select 4, 1, 10, 'C' union all
select 5, 2, 20, 'A' union all
select 6, 3, 50, 'A' union all
select 7, 3, 50, 'A' union all
select 8, 4, 20, 'B' union all
select 9, 5, 10, 'A'


select a.flag,a.flagCount,b.valueSum
from 
(select t1.flag,count(*) 'flagCount'
 from sup t1 group by t1.flag) a
cross apply
((select sum(value) 'valueSum' from
  (select distinct flag,number,value from sup) t2
  where t2.flag=a.flag)) b
 
 flag flagCount   valueSum
---- ----------- -----------
 A    6           90
 B    2           30
 C    1           10

------解决方案--------------------
SQL code

declare @T table
(id int,number int,value int,flag varchar(1))
insert into @T
select 1,1,10,'A' union all
select 2,1,10,'A' union all
select 3,1,10,'B' union all
select 4,1,10,'C' union all
select 5,2,20,'A' union all
select 6,3,50,'A' union all
select 7,3,50,'A' union all
select 8,4,20,'B' union all
select 9,5,10,'A'

select flag,
(select count(1) from @T where flag=a.flag) as flagCount ,
sum(value) as valueSum
from (select distinct number,value,flag from @T)a group by flag
/*
flag flagCount   valueSum
---- ----------- -----------
A    6           90
B    2           30
C    1           10
*/

------解决方案--------------------
SQL code
select a.flag,a.flagCount,sum(b.value) as valueSum
from (select flag,count(1) as flagCount from tb group by flag) a
join (select distinct number,value,flag from tb) b
on a.flag=b.flag
group by a.flag,a.flagCount

/**
flag       flagCount   valueSum
---------- ----------- -----------
A          6           90
B          2           30
C          1           10

(3 行受影响)
**/