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
 Count(Expression)

Author  Topic 

olibara
Yak Posting Veteran

94 Posts

Posted - 2012-02-16 : 04:50:17
Hello

I'm using SQL Server 2008
I need to know if it is possible to use expression in a Count()

The purpose is to count the number of row for a specific value
For example

Select 
Name
,COUNT([date]>'20110101') AS Since2011
,COUNT([date]>'20120101') AS Since2012
FROM MyTable
GROUP BY Name


Thank for your help

DonAtWork
Master Smack Fu Yak Hacker

2167 Posts

Posted - 2012-02-16 : 09:19:01
perhaps this
Select 
Name
,SUM(CASE WHEN [date]>'20110101' THEN 1 ELSE 0 END) AS Since2011
,SUM(CASE WHEN [date]>'20120101' THEN 1 ELSE 0 END) AS Since2012
FROM MyTable
GROUP BY Name


http://weblogs.sqlteam.com/jeffs/archive/2008/05/13/question-needed-not-answer.aspx
How to ask: http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

For ultra basic questions, follow these links.
http://www.sql-tutorial.net/
http://www.firstsql.com/tutor.htm
http://www.w3schools.com/sql/default.asp
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2012-02-16 : 09:45:42
You don't want a range?

You will double count 2011

Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx


Want to help yourself?

http://msdn.microsoft.com/en-us/library/ms130214.aspx

http://weblogs.sqlteam.com/brettk/

http://brettkaiser.blogspot.com/


Go to Top of Page

olibara
Yak Posting Veteran

94 Posts

Posted - 2012-02-16 : 10:19:00
Thank you DontAtWork

Indeed

But I use a count this way
count(case WHEN [date] > '20111001' then 1 end)

Thank you Brett
No I do not really need a range (the name of the fields are Since2011 and Since2012 : obviously 2012 is contained in Since2011)
Go to Top of Page
   

- Advertisement -