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 2005 Forums
 Transact-SQL (2005)
 Problem with WHERE clause?

Author  Topic 

NateEmlen
Starting Member

2 Posts

Posted - 2011-05-13 : 11:56:00
I am relatively new in using SQL syntax, and can usually figure things out just by using google, but on this one I don't even know what to search for. I have several different tables with data in them, some of which have common fields that need to be added together. My SQL code works fine, but if one of the tables does not have a record for that particular date, the query will not execute (I am working in a factory so machines periodically are shut off for maintanence). The following is my code:

SELECT
(West_PET_Blender_South.PET + West_PET_Blender_North.PET +
South_PET_Blender.PET) AS PET,
(West_PET_Blender_South.PCR + West_PET_Blender_North.PCR) AS PCR,
(West_PET_Blender_South.Regrind + West_PET_Blender_North.Regrind +
South_PET_Blender.Regrind) AS Regrind

FROM West_PET_Blender_South, West_PET_Blender_North,
South_PET_Blender

WHERE (West_PET_Blender_South.Production_Date = :Date1) AND
(West_PET_Blender_South.Shift = :Shift1) AND
(West_PET_Blender_North.Production_Date = :Date2) AND
(West_PET_Blender_North.Shift = :Shift2) AND
(South_PET_Blender.Production_Date = :Date3) AND
(South_PET_Blender.Shift = :Shift3)

Lets say the South PET Blender has been down, and there is no record for that day, the code will not execute. There is probably a very simple solution for this, but this is not what I went to school for . Thanks.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-05-13 : 13:02:34
You'll need to use an OUTER JOIN, preferably LEFT JOIN.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

NateEmlen
Starting Member

2 Posts

Posted - 2011-05-13 : 14:16:35
If I use JOIN, then the query works but when I add the null values to the other numbers, the result is zero. Is there a way to change all the nulls to 0?
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-05-13 : 15:32:24
Yes, but please show us some sample data to help (before and after examples).

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

Bustaz Kool
Master Smack Fu Yak Hacker

1834 Posts

Posted - 2011-05-13 : 16:46:22
IsNull(MyColumn, 0) or coalesce(MyColumn, 0)

=======================================
Elitism is the slur directed at merit by mediocrity. -Sydney J. Harris, journalist (1917-1986)
Go to Top of Page
   

- Advertisement -