If I insert the following values into my table
Insert into Table1 (Field1, Field2, Field3, Field4, DateField) values (1, 1, 100, 5, "5/10/2012")
Insert into Table1 (Field1, Field2, Field3, Field4, DateField) values (1, 2, 100, 99, "5/10/2012")
Insert into Table1 (Field1, Field2, Field3, Field4, DateField) values (1, 3, 100, 3, "5/10/2012")
What my query is going to try and get is the value from Field4 with the maximum value in Field2 by a certain date.
Example
select isnull(Field4,0) from Table1
where Field1 = 1 and Field3 = 100 and datediff(day,DateField,"5/21/2012") > 0
having Max(Field2) = Field2
Which works great. I get 3 which is expected. Now this is where my questions comes from. It is possible Field3 could have other values, such as 110. When I run that query
select isnull(Field4,0) from Table1
where Field1 = 1 and Field3 = 110 and datediff(day,DateField,"5/21/2012") > 0
having Max(Field2) = Field2
I don’t get any results. It should be null, and the isnull(Field4,0) should then spit out 0. But it doesn’t. I’ve tried replacing the selection with count(*) to see if it returns 0, but it doesn’t return anything. I’m at a loss. I need it to return 0 as this will be going into a temp table and then summed up with values from another table. Thanks.
Edit – New question part
I understand that I may have been using the isnull for the wrong thing here. Which I can accept. However, if I wanted to write a case statement to handle nothing being returned, it doesn’t return 0 if no rows are returned.
select count(*) from Table1
where Field1 = 1 and Field3 = 110 and datediff(day,DateField,"5/21/2012") > 0
having Max(Field2) = Field2
The above code doesn’t return anything, instead of 0 like I would think it would.
You do not get any results because none of the 3 records you inserted has 110 for Field3. As a result, no rows are returned from the query. Your
ISNULLwould only be used if instead of 5, 99, or 3, those values wereNULLfor a row returned.If this record was in your table:
This record would match your
Field3 = 110requirement, and then have Field4 Null, being set to 0 by your SELECT logic, but since it is not, nothing will be returned by your query.Part 2
It appears that the
HAVINGis removing the0record from the result set since no records are left after theWHEREclause to match against theHAVINGcriteria.If you want to see whether any results match your criteria, you can use the EXISTS clause