22,207
社区成员
发帖
与我相关
我的任务
分享
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[name] varchar(1),[type] varchar(5),[money] int)
insert [tb]
select 1,'s','xxx',100 union all
select 2,'s','sdsds',100 union all
select 3,'s','ssss',100 union all
select 4,'m','sss',90 union all
select 5,'z','sss',80
--select * from [tb]
select id=min(id)
,name
,type=case count(*) when 1 then 'Single-Row' else 'Multi-Row' end
,money=sum(money)
from tb
group by name
order by id
--测试结果:
/*
id name type money
----------- ---- ---------- -----------
1 s Multi-Row 300
4 m Single-Row 90
5 z Single-Row 80
(3 行受影响)
*/
select min(id)
,name
,case when count(*)>1 then 'multi-row' else 'single-row'
,sum(money)
from table
group by name
--> --> (让你望见影子的墙)生成測試數據
if not object_id('tb') is null
drop table tb
Go
Create table tb([id] int,[name] nvarchar(1),[type] nvarchar(5),[money] int)
Insert tb
select 1,N's',N'xxx',100 union all
select 2,N's',N'sdsds',100 union all
select 3,N's',N'ssss',100 union all
select 4,N'm',N'sss',90 union all
select 5,N'z',N'sss',80
Go
Select * from tb
select distinct id =(select min (id) from tb where name=t.name),
name,
type=case when (select count(*) from tb where name=t.name)>1 then 'Multi-Row' else 'single-row' end,
money=(select sum(money) from tb where name=t.name)
from tb t
1 s Multi-Row 300
4 m single-row 90
5 z single-row 80
select distinct id =(select min (id) from tb where name=t.name),
name,
type=case when (select count(*) from tb where type=t.type)>1 then 'Multi-Row' else 'single-row' end,
money=(select sum(money) from tb where name=t.name)
from tb t
1 s single-row 300
4 m Multi-Row 90
5 z Multi-Row 80
declare @t table (id int,names varchar,types varchar(10),moneys int)
insert @t select 1,'s','xxx',100
union all select 2,'s','sdsds',100
union all select 3,'s','ssss',100
union all select 4,'m','sss',90
union all select 5,'z','sss',80
select min(id) as id,
names,
types=(case when count(names)>1 then 'multi' else 'single' end),
sum(moneys) as moneys
from @t
group by names
order by 1
select id,name,type,sum(money) as money from table group by name