34,594
社区成员
发帖
与我相关
我的任务
分享
就是我有一张表A1如下:
ID Name
01 A
02 B
03 C
04 A
05 B
06 B
08 A
我希望查出来的结果是表A2:
name count1 count2 count3
A 2 1
B 1 2
C 1
解释下,A2表中的count1,表示在表A1中id小于5的A出现次数为2,B出现次数为1,C出现次数为1.
count2表示,id在5-6之间,ABC出现的次数
count3表示,id在6以上,ABC出现的次数。
declare @Tb TABLE ([ID] VARCHAR(2),[Name] VARCHAR(1))
INSERT @Tb
SELECT '01','A' UNION ALL
SELECT '02','B' UNION ALL
SELECT '03','C' UNION ALL
SELECT '04','A' UNION ALL
SELECT '05','B' UNION ALL
SELECT '06','B' UNION ALL
SELECT '08','A'
select
[Name] ,
isnull(rtrim(sum(case when [ID]<'05' then 1 end)),'') as count1,
isnull(rtrim(sum(case when [ID] in ( '05' , '06') then 1 end)),'') as count2,
isnull(rtrim(sum(case when [ID]>'05' then 1 end)),'') as count3
from @Tb
group by [Name]
/*
Name count1 count2 count3
A 2 1
B 1 2 1
C 1
*/
select name
count(case when ID<5 then 1 else null end) count1,
count(case when ID between 5 and 6 then 1 else null end) count2,
count(case when ID>6 then 1 else null end) count3
from A1
group by name;
--> 测试数据:[tb]
IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb]
GO
CREATE TABLE [tb]([ID] VARCHAR(2),[Name] VARCHAR(1))
INSERT [tb]
SELECT '01','A' UNION ALL
SELECT '02','B' UNION ALL
SELECT '03','C' UNION ALL
SELECT '04','A' UNION ALL
SELECT '05','B' UNION ALL
SELECT '06','B' UNION ALL
SELECT '08','A'
--------------开始查询--------------------------
select name,
sum(case when id<5 then 1 else 0 end) as count1,
sum(case when id>=5 and id<=6 then 1 else 0 end) as count2,
sum(case when id>6 then 1 else 0 end) as count3
from tb
group by name
----------------结果----------------------------
/*
name count1 count2 count3
---- ----------- ----------- -----------
A 2 0 1
B 1 2 0
C 1 0 0
(3 行受影响)
*/
select Name,
sum(case when id<5 then 1 else 0 end) as count1,
sum(case when id>=5 and id<=6 then 1 else 0 end) as count2,
sum(case when id>6 then 1 else 0 end) as count3
from tb
group by name
select name
count(case when ID<5 then 1 else null end) count1,
count(case when ID between 5 and 6 then 1 else null end) count2,
count(case when ID>6 then 1 else null end) count3
from A1
group by name;
select name
count(case when ID<5 then 1 else null end) count1,
count(case when ID between 5 and 6 then 1 else null end) count2,
count(case when ID>6 then 1 else null end) count3
from A1
group by name;
select Name,
sum(case when id<5 then 1 else 0 end) as count1,
sum(case when id>=5 and id<6 then 1 else 0 end) as count2,
sum(case when id>6 then 1 else 0 end) as count3
from tb
group by name