Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Combining columns from query

Author  Topic 

tim8w
Starting Member

10 Posts

Posted - 2011-09-02 : 14:48:25
I have a Table that contains two fields, Name and Status.

Each record can contain identical entries for Name and Status, i.e.

Name Status
Person1 1
Person1 2
Person1 1
Person1 3
Person2 1
Person2 3
Person3 1

After the query, I need the following output:

Name Count (where Status = 1 or 3)
Person1 3
Person2 2
Person3 1

Is such a query possible?

So far the best I have is:

SELECT Name, Status, COUNT(*) AS Count
FROM Table
GROUP BY Name, Status
HAVING (Status IN (1,3))
ORDER BY Name

But this query produces:

Name Status Count (where Status = 1 or 3)
Person1 1 2
Person1 3 1
Person2 1 1
Person2 3 1
Person3 1 1


Any ideas?

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-09-02 : 14:54:23
SELECT Name, COUNT(*) AS Count
FROM Table
WHERE Status IN (1,3)
GROUP BY Name
ORDER BY Name

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -