M99
M99

Reputation: 1907

Help with SQL Query Count

I have a table similar to the following

ID NUMBER
VAL1 NUMBER
VAL2 NUMBER

I need an SQL query that displays count of rows that have VAL1 > VAL2 and Count of rows that have VAL1 < VAL2. Both counts using one SQL query. Thanks.

Upvotes: 2

Views: 150

Answers (3)

D&#39;Arcy Rittich
D&#39;Arcy Rittich

Reputation: 171391

This query should work with most database platforms:

 select sum(case when val1 > val2 then 1 end) as GreaterThanCount,
    sum(case when val1 < val2 then 1 end) as LessThanCount
from MyTable

To show the sums in separate rows, you can do:

select case when val1 > val2 then 'GreaterThan' else 'LessThan' end as Type,
    count(*) as Count
from MyTable    
group by case when val1 > val2 then 'GreaterThan' else 'LessThan' end

Upvotes: 4

mrkmg
mrkmg

Reputation: 241

SELECT SUM(VAL1 > VAL2) as arg1, SUM(VAL1 < VAL2) as arg2

Upvotes: 1

duffymo
duffymo

Reputation: 308753

Try this:

select id, count(VAL1 > VAL2) as more1, count(val2 > val1) as more2
from your_table

Upvotes: 0

Related Questions