0

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

3
  • Is Status column dynamic? Is that fix that it will contain 1,2,3 only? Commented Dec 7, 2016 at 11:21
  • Nope, it's not fix Commented Dec 7, 2016 at 12:01
  • Then see my ans in Answers.. that can help you with different values Commented Dec 7, 2016 at 12:02

2 Answers 2

4

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]
Sign up to request clarification or add additional context in comments.

Comments

3

Try this, This is dynamic

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

2 Comments

Upvoted... But changes the result format.. probably OP can follow this format which avoid's hard coding
Thank you for your vote @prdp but converting it to pivot would also get ugly.so i kept it this way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.