March 9, 2011 at 10:42 am
i would like to find out how to do a single query to return the count total for both values
table1
c1,c2
'sample1',0
'sample2',0
'sample2',1
'sample3',1
'sample4',0
'sample4',1
'sample4',0
'sample4',1
'sample4',1
would like to return something along the lines of
text, total_0s, total_1s
sample1, 1, 0
sample2, 1, 1
sample3, 0, 1
sample4, 2, 3
Thanks for any guidance...
March 9, 2011 at 10:46 am
Does the "sample1" value reference something in a lookup table? If so, you can query that, and then two inline-subqueries will get you the counts.
If not, a query like this will work:
select c1, sum(case when c2 = 0 then 1 else 0 end) as total_0s, sum(case when c2 != 0 then 1 else 0 end) as total_1s
from MyTable
group by c1;
- Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
Property of The Thread
"Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon
March 9, 2011 at 10:46 am
I assume this is a bit field?
select COUNT(*) - sum(cast(c2 as Int)) as Zero,
sum(cast(c2 as Int)) as One
from table1
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
March 9, 2011 at 10:47 am
nevermind, I missed the grouping. Gus's is the correct way. I misread and thought you were just looking for a total count. :blush:
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
March 9, 2011 at 11:05 am
Thats what i needed thanks again for the info/example. worked great.
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply