简体   繁体   中英

t-sql 2008 r2 where statement with several not items

In t-sql 2008 r2, I am trying to determine how to setup the sql to accomplish the following goal:

SELECT table1.customer_id, 
       type, 
       start_date, 
       end_date, 
       program_id 
FROM   table1 
       JOIN table2 
         ON table1.customer_id = table2.customer_id 
  1. where type not= ('aa','cc') and type not = 'g2' where code = 3 In table1 there are lots of records for each customer_id and there can be lots of various values for type. I only want the customer_ids that do not contain the values listed above. and
  2. table2 has only one customer_id. Customer_id is the key of table2. I want customers that do not have a value in one of the 3 columns: start_date, end_date, and program_id.

Both parts 1 and 2 listed above need to be true for the customer_id to be selected. Thus can you tell me how to setup that sql?

I cannot tell you exactly because I cannot see your database structure but I believe it would be something like this:

   SELECT table1.customer_id,type,start_date,end_date,Program_id
    FROM table1 JOIN table2 ON table1.customer_id = table2.customer_id
    WHERE (table1.type NOT IN('aa', 'cc', 'g2') AND table1.code = 3)
    AND (table2.start_data IS NULL OR table2.end_date IS NULL OR table2.program_id IS NULL)

Give the check to Jason(+1) but I would pull conditions into the join
Sometimes that helps the query optimizer

SELECT table1.customer_id,type,start_date,end_date,Program_id
  FROM table1 
  JOIN table2 
    ON table1.customer_id = table2.customer_id
   AND table1.type NOT IN ('aa', 'cc') 
   AND (table1.code = 3 and table1.type <> 'g2')
   AND (table2.start_data IS NULL OR table2.end_date IS NULL OR table2.program_id IS NULL)

I get this is what you are literally asking for but it is not what you think it is

AND table1.type NOT IN ('aa', 'cc') 
AND (table1.code = 3 and table1.type <> 'g2')

is the same as

AND table1.type NOT IN ('aa', 'cc')
AND table1.type <> 'g2' 
AND table1.code = 3 

is the same as

AND table1.type NOT IN ('aa', 'cc', 'g2')
AND table1.code = 3

I think what you mean to ask for is something like

AND (    table1.type NOT IN ('aa', 'cc') 
      or (table1.code = 3 and table1.type <> 'g2') 
    )

How about trying to use the INNER JOIN:

SELECT table1.customer_id,type,start_date,end_date,Program_id
  FROM table1 
INNER JOIN table2 ON table1.customer_id = table2.customer_id
  WHERE table1.type != 'aa' 
    AND  table1.type != 'cc' 
    AND table1.type != 'g2'
    AND table1.code = 3
   AND (table2.start_data IS NULL OR table2.end_date IS NULL OR table2.program_id IS NULL)

Let me know if it works fine with you!

Regrads, ANDOURA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM