Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL statement to generate column values

Tags:

sql

sql-server

Please see the DDL below:

 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)

I am looking for a result like this:

2 1 1 1 1

The following criteria generates this result:

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)
like image 483
w0051977 Avatar asked Mar 17 '23 03:03

w0051977


1 Answers

Use CASE to SUM different Type's

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
like image 64
jarlh Avatar answered Mar 23 '23 02:03

jarlh