views:

238

answers:

1

Is there a way to use the HAVING clause in some other way without using group by.

I am using rails and following is a sample sccenario of the problem that i am facing. In rails you can use the Model.find(:all,:select,conditions,:group) function to get data. In this query i can specify a having clause in the :group param. But what if i dont have a group by clause but want to have a having clause in the result set.

Ex: Lets take a query

select sum(x) as a,b,c from y where "some_conditions" group by b,c;

This query has a sum() aggregation on one of the fields. No if there is nothing to aggregate then my result should be an empty set. But mysql return a NULL row. So this problem can be solved by using

select sum(x) as a,b from y where "some_conditions" group by b having a NOT NULL;

but what happens in case i dont have a group by clause?? a query like below

select sum(x) as a,b from y where "some_conditions";

so how to specify that sum(x) should not be NULL?

Any solution that would return an empty set in this case instead of a NULL row will help and also that solution should be doable in rails.

We can use subqueries to get this condition working with sumthin like this

select * from ((select sum(x) as b FROM y where "some_condition") as subq) where subq.b is not null;

but is there a better way to do this thru sql/rails ??

A: 

The sub query is the standard way to handle this situation in SQL. However, I recommend that you don't use the sub query or HAVING, and instead check to see if SUM(x) is NULL. It's best to always return a result so you don't have to check to see if you have one or not. If the value is NULL, then you know there were no records with NON NULL values.

One thing you didn't mention, if you don't want sum(x) to be null then you can do this:

SELECT IFNULL(SUM(x), 0) AS a FROM table
Marcus Adams
@marcus adams - that works! thanks!
meetraghu28