January 31, 2014 at 2:13 pm
Hi,
I've been writing queries using
SUM(CASE WHEN SomeVal = 'X' THEN 1 ELSE 0 END)
And today looking at some code I saw someone do
CASE WHEN SomeVal = 'X' THEN COUNT(*)
Is there any reason to use one over the other?
Thanks
January 31, 2014 at 2:41 pm
sqldriver (1/31/2014)
Hi,I've been writing queries using
SUM(CASE WHEN SomeVal = 'X' THEN 1 ELSE 0 END)
And today looking at some code I saw someone do
CASE WHEN SomeVal = 'X' THEN COUNT(*)
Is there any reason to use one over the other?
Thanks
There do slightly different things. The first value does not require this to be part of the group by. It will get a count of all rows in your query where SomeVal = 'X'.
The second query means that you have to include SomeVal in your group by.
Does that make sense?
_______________________________________________________________
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/
January 31, 2014 at 2:47 pm
Yep, thanks Sean. I usually end up with an ID or similar column to group by in SUM(CASE...) anyway, so it's not a total departure.
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply