34,576
社区成员
发帖
与我相关
我的任务
分享
if not object_id('Tempdb..#tb') is null
drop table #tb
Go
Create table #tb([姓名] nvarchar(2),[类型] nvarchar(1))
Insert #tb
select N'小王',N'A' union all
select N'小王',N'C' union all
select N'小红',N'B' union all
select N'李四',N'A' union all
select N'张三',N'C' union all
select N'小王',N'C' union all
select N'小王',N'B' union all
select N'小王',N'C' union all
select N'小红',N'C' union all
select N'李四',N'C'
Go
Select [姓名],
[A],
[B],
[C],
A+B+C as Total
from #tb
pivot (count([类型]) for [类型] in([A],[B],[C] ))AS P
/*
姓名 A B C Total
---- ----------- ----------- ----------- -----------
小王 1 1 3 5
小红 0 1 1 2
李四 1 0 1 2
张三 0 0 1 1
(4 row(s) affected)
*/
select 姓名,SUM((case when 类型='A' then 1 else 0 end)) as 'A',
SUM((case when 类型='B' then 1 else 0 end)) as 'B',
SUM((case when 类型='C' then 1 else 0 end)) as 'C',
count(*) as 总和
from 表
group by 姓名
--姓名 类型
--小王 A
--小王 C
--小红 B
--李四 A
--张三 C
--小王 C
--小王 B
--小王 C
--小红 C
--李四 C
if OBJECT_ID('tb')is not null
drop table tb
go
CREATE TABLE tb(姓名 varchar(50), 类型 varchar(50))
insert into tb values('小王', 'A')
insert into tb values('小王' ,'C')
insert into tb values('小红', 'B')
insert into tb values('李四', 'A')
insert into tb values('张三', 'C')
insert into tb values('小王', 'C')
insert into tb values('小王' ,'B')
insert into tb values('小王', 'C')
insert into tb values('小红', 'C')
insert into tb values('李四', 'C')
--要求结果
--姓名 A B C
--小王 1 1 3
--小红 0 1 1
--李四 1 0 1
--张三 0 0 1
SELECT 姓名
,(select count(类型) from tb where 姓名=t.姓名 and 类型='A') AS A
,(select count(类型) from tb where 姓名=t.姓名 and 类型='B') AS B
,(select count(类型) from tb where 姓名=t.姓名 and 类型='C') AS C
FROM tb t GROUP BY 姓名
姓名 A B C
-------------------------------------------------- ----------- ----------- -----------
李四 1 0 1
小红 0 1 1
小王 1 1 3
张三 0 0 1
(4 行受影响)
if not object_id('Tempdb..#tb') is null
drop table #tb
Go
Create table #tb([姓名] nvarchar(2),[类型] nvarchar(1))
Insert #tb
select N'小王',N'A' union all
select N'小王',N'C' union all
select N'小红',N'B' union all
select N'李四',N'A' union all
select N'张三',N'C' union all
select N'小王',N'C' union all
select N'小王',N'B' union all
select N'小王',N'C' union all
select N'小红',N'C' union all
select N'李四',N'C'
Go
Select [姓名],
[A],
[B],
[C]
from #tb
pivot (count([类型]) for [类型] in([A],[B],[C] ))AS P
/*
姓名 A B C
---- ----------- ----------- -----------
小王 1 1 3
小红 0 1 1
李四 1 0 1
张三 0 0 1
(4 row(s) affected)
*/
select 姓名,
sum(case when 类型='A' then 1 else 0 end) A,
sum(case when 类型='A' then 1 else 0 end) B,
sum(case when 类型='A' then 1 else 0 end) C
from tb
group by 姓名
select 姓名,SUM((case when 类型='A' then 1 else 0 end)) as 'A',
SUM((case when 类型='B' then 1 else 0 end)) as 'B',
SUM((case when 类型='C' then 1 else 0 end)) as 'C'
from 表
group by 姓名