Tuesday, March 27, 2012

Count if Conditions Met

I am trying to do a summary SQL query. I have 3 fields. If one filed is
null and the other is not null, I want to count how many records there
are. I also want to count the opposite way then count both fields if
they are both not null. Can I do this within the same query? Help
appreciated.

Thanks,
Steve

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!You could use a CASE expression inside SUM/COUNT etc. Here's an example:

CREATE TABLE #x(i int, j int)
INSERT #x SELECT NULL, 1
INSERT #x SELECT 1, 2
INSERT #x SELECT 2, 3
INSERT #x SELECT NULL, 4
INSERT #x SELECT NULL, 5

SELECT SUM(CASE WHEN i IS NULL THEN 0 ELSE j END) FROM #x

Next time, please post your table structures and some sample data, along
with your desired output.
--
Vyas, MVP (SQL Server)
http://vyaskn.tripod.com/

"Steve Bishop" <steveb@.viper.com> wrote in message
news:411a5f99$0$14487$c397aba@.news.newsgroups.ws.. .
> I am trying to do a summary SQL query. I have 3 fields. If one filed is
> null and the other is not null, I want to count how many records there
> are. I also want to count the opposite way then count both fields if
> they are both not null. Can I do this within the same query? Help
> appreciated.
> Thanks,
> Steve
> *** Sent via Developersdex http://www.developersdex.com ***
> Don't just participate in USENET...get rewarded for it!|||You could use a CASE expression inside SUM/COUNT etc. Here's an example:

CREATE TABLE #x(i int, j int)
INSERT #x SELECT NULL, 1
INSERT #x SELECT 1, 2
INSERT #x SELECT 2, 3
INSERT #x SELECT NULL, 4
INSERT #x SELECT NULL, 5

SELECT SUM(CASE WHEN i IS NULL THEN 0 ELSE j END) FROM #x

Next time, please post your table structures and some sample data, along
with your desired output.
--
Vyas, MVP (SQL Server)
http://vyaskn.tripod.com/

"Steve Bishop" <steveb@.viper.com> wrote in message
news:411a5f99$0$14487$c397aba@.news.newsgroups.ws.. .
> I am trying to do a summary SQL query. I have 3 fields. If one filed is
> null and the other is not null, I want to count how many records there
> are. I also want to count the opposite way then count both fields if
> they are both not null. Can I do this within the same query? Help
> appreciated.
> Thanks,
> Steve
> *** Sent via Developersdex http://www.developersdex.com ***
> Don't just participate in USENET...get rewarded for it!

No comments:

Post a Comment