简体   繁体   中英

Select multiple columns of count for different column value

I have tables like this:

ID          Status
----------- -----------------
a            3
b            3
c            1
d            2
e            1

How can i query it such that the count for each status is in 1 column:

Status=1  Status=2   Status=3
--------  --------  --------
2          1          2

is it necessary to Select from multiple Select of Count here? NOTE: the Status is not fixed and may contain values besides 1, 2 and 3

Use Conditional Aggregate

select count(case when Status = 1 then 1 end) as [Status=1],
       count(case when Status = 2 then 1 end) as [Status=2],
       count(case when Status = 3 then 1 end) as [Status=3]
From yourtable 

same count can be achieved through SUM aggregate

Sum(case when Status = 1 then 1 else 0 end) as [Status=1]

试试这个,这是动态的

select 'Status = '+cast(Status as varchar(200)) Status,count(Status) Count from yourtable group by Status

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM