August 31, 2015 at 4:10 pm
Using MSSQL 2012
I have a simple select query and I need to eliminate records whose values from 2 different fields match. I thought I had this working, but if one of those fields in my data IS NULL it filters out those records. If I comment out my last line then my number record shows, if I include that statement that record drops. The only thing I see in my data is the Name and PName are both NULL in the data for that particular number. Just need to filter out any records where it finds those 3 Names that also have "Default" as the PName, then include everything else even if Name or Pname is NULL.
Below is my where clause.
WHERE [DETERMINATION] <> 'Denied'
AND [Number] ='A150731000039'
---- Removes incorrect records where these names match----
AND ([Name] NOT IN ('GLASSMAN','NANCY','LUDEMANN') AND [PName] = 'DEFAULT')
Thanks,
GJ
August 31, 2015 at 4:42 pm
Glenn,
any chance you could provide a create table script and some dummy records? Are all the records in the same table?
thanks,
Pieter
September 1, 2015 at 2:10 am
Hi,
if you want to include all rows except those mentioned in the last line, and want to retain rows with NULL values in the resultset, you will need something like this:
AND (ISNULL([Name],'XXX') NOT IN ('GLASSMAN','NANCY','LUDEMANN') AND ISNULL([PName],'DEFAULT') = 'DEFAULT')
September 1, 2015 at 2:23 am
Just re-read your post and I think you have one more problem in your query.
In words you have stated "to filter out any records where it finds those 3 Names that also have "Default" as the PName", but that is not what you have written in the code. What you have written in code means, that ALL rows that have anything else than DEFAULT in PName will be filtered out - not only those that match the NOT IN ('GLASSMAN','NANCY','LUDEMANN') condition.
So, if I understand correctly, you would probably need this:
AND (ISNULL([Name],'XXX') NOT IN ('GLASSMAN','NANCY','LUDEMANN') OR ISNULL([PName],'XXX') <> 'DEFAULT')
September 1, 2015 at 7:31 am
WHERE [DETERMINATION] <> 'Denied'
AND [Number] ='A150731000039'
---- Removes incorrect records where these names match----
AND (
[Name] IS NULL
OR [PName] IS NULL
OR ([Name] NOT IN ('GLASSMAN','NANCY','LUDEMANN') AND [PName] = 'DEFAULT')
)
Avoid using ISNULL() in the WHERE clause; Google "SARGable".
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply