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
 Nested Select with Count

Author  Topic 

smifsud
Starting Member

2 Posts

Posted - 2009-01-26 : 07:49:49
I am very new to SQL so please forgive if this query is very easy.

I need to get information out of one table about who is deal with an issue. Up to three people can be dealing with an issue but I need a single figure for how many issues are being dealt with by person X. I will explain with a sample table.

Job - Person 1 - Person 2 - Person 3
----------------------------------------------------
Painting - Tony - Dave - Paul
Cleaning - Steve - Tony - Dave
Sweeping - Dave - Paul
DIY - Tony - Dave

Desired Output
-----------------
Tony - 3
Dave - 4
Paul - 2
Steve - 1

I can do the count on one field but do not know how to nest a query and get only one result.

I hope that someone can help.

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2009-01-26 : 08:04:25
[code]SELECT Person,
COUNT(*)
FROM (
SELECT Person1 AS Person
FROM Table1

UNION ALL

SELECT Person2 AS Person
FROM Table1

UNION ALL

SELECT Person3 AS Person
FROM Table1
) AS d
GROUP BY Person[/code]


E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-01-26 : 08:19:38
If sql 2005

SELECT Name,
COUNT(Job)
FROM (SELECT * FROM YourTable)m
UNPIVOT(Name FOR Person IN ([Person 1],[Person 2],[Person 3]))u
GROUP BY Name
Go to Top of Page

smifsud
Starting Member

2 Posts

Posted - 2009-01-26 : 09:23:21
Peso, you are a genius – exactly what I wanted.

Thank you
Go to Top of Page
   

- Advertisement -