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
 SQL Server 2012 Forums
 Transact-SQL (2012)
 multiple counts

Author  Topic 

esthera
Master Smack Fu Yak Hacker

1410 Posts

Posted - 2013-05-17 : 03:28:04
i have a table

name
response
response2
response3

now i want to make query where i retur

name response response2 response3

and for each name i put the count of how many records had a response for each of them


can i do a group by with a count of different fields where they are not null?

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2013-05-17 : 03:33:26
You can use COUNT(Specific ColumnName) OVER(PARTITION BY name)

--
Chandu
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-05-17 : 03:38:50
[code]
SELECT name,
SUM(CASE WHEN response > '' THEN 1 ELSE 0 END) AS response,
SUM(CASE WHEN response2 > '' THEN 1 ELSE 0 END) AS response2,
SUM(CASE WHEN response3 > '' THEN 1 ELSE 0 END) AS response3
FROM Table
GROUP BY name
[/code]



------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-05-17 : 03:39:39
if you want to make it dynamic

http://sqlblogcasts.com/blogs/madhivanan/archive/2007/08/27/dynamic-crosstab-with-multiple-pivot-columns.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

Bustaz Kool
Master Smack Fu Yak Hacker

1834 Posts

Posted - 2013-05-17 : 18:32:48
If your "empty" are indeed NULL then you can use:[CODE]select count(*) cAll, count(response) cnt1, count(response2) cnt2, count(response3) cnt3
from MyTable[/CODE]The aggregate functions ignore null columns (except count(*) of course).

=================================================
I am not one of those who in expressing opinions confine themselves to facts. (Mark Twain)
Go to Top of Page

esthera
Master Smack Fu Yak Hacker

1410 Posts

Posted - 2013-05-19 : 05:34:36
thanks - these were very helpful responses
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-05-20 : 01:13:35
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -