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 2000 Forums
 Transact-SQL (2000)
 Logical expressions with aggregate functions?

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2005-10-10 : 07:33:46
Sam Ellis writes "Is there a way to use logical expressions to alter the output of aggregate functions?

For example, this query returns the total number of rows in column1 and column2:

select count(column1) as col1count, count(column2) as col2count
from mytable
order by col2count

But what if I only want to count the number of rows in column1 which are less than 10, and only count the rows in column2 which are more than 30? Is there a way to do this within a single query, so that I can easily order the results?"

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-10-10 : 07:37:24
Try this

select Sum(case when column1<=10 then 1 else 0 end) as col1count, Sum(case when column2>30 then 1 else 0 end) as col2count from mytable order by col2count


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -