2

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.

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to display the counts in two different rows with the same SQL query?
Note that rows where val1 = val2 are caught in the "LessThan" bucket here.
1

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

1 Comment

Is it possible to display the counts in two different rows with the same SQL query?
0

Try this:

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

1 Comment

Is it possible to display the counts in two different rows with the same SQL query?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.