用于生成列值的SQL语句

w00*_*977 4 sql sql-server

请参阅下面的DDL:

 create table Person (ID int, [Type] int)
 insert into Person values (1,1)
 insert into Person values (2,1)
 insert into Person values (3,2)
 insert into Person values (4,3)
 insert into Person values (5,4)
 insert into Person values (6,5)
Run Code Online (Sandbox Code Playgroud)

我正在寻找这样的结果:

2 1 1 1 1
Run Code Online (Sandbox Code Playgroud)

以下条件生成此结果:

There are 2 persons with a type of 1 (The first column value is: 2)
There is 1 person with a type of 2 (The second column value is: 1)
There is 1 person with a type of 3 (The third column value is: 1)
There is 1 person with a type of 4 (The forth column value is: 1)
There is 1 person with a type of 5 (The fifth column value is: 1)
Run Code Online (Sandbox Code Playgroud)

jar*_*rlh 6

使用CASESUM不同类型的

select sum(case when [Type] = 1 then 1 else 0 end),
       sum(case when [Type] = 2 then 1 else 0 end),
       sum(case when [Type] = 3 then 1 else 0 end),
       sum(case when [Type] = 4 then 1 else 0 end),
       sum(case when [Type] = 5 then 1 else 0 end)
from tablename
Run Code Online (Sandbox Code Playgroud)