Domanda

I'm trying to use an IN clause, however the filtering needs to be on a set of items defined by 2 columns. Is this possible? There are probably other ways to do this (e.g. table variable), but I'd like to do it as an IN clause, if possible, because that would be more elegant and simpler to dynamically create in my application.

This psuedo code might make it clearer what I'm trying to do.

SELECT *
FROM Distributors
WHERE (City,State) IN (('Springfield','OH'), ('Springfield','MO'), ('Houston','TX'))
È stato utile?

Soluzione 2

select * 
from distributors
where  ( city = 'Springfield' and State = 'OH') OR
       ( city = 'Springfield' and State = 'MO') OR
       ( city = 'Houston' and State = 'TX')

not so complicated

Altri suggerimenti

Easiest is probably to produce a pseudo-table and perform a join to it. Either VALUES (SQL Server 2008 or later):

SELECT d.*
FROM Distributors d
JOIN (VALUES ('Springfield','OH'), ('Springfield','MO'), ('Houston','TX'))
    as t(City,State)
ON d.City = t.City and d.State = t.State

Or UNION ALL:

SELECT d.*
FROM Distributors d
JOIN (SELECT 'Springfield','OH' UNION ALL SELECT 'Springfield','MO' UNION ALL SELECT 'Houston','TX')
    as t(City,State)
ON d.City = t.City and d.State = t.State

I admit, I'm not using IN any more, but the separators between the varying elements are all identical (in either case), so hopefully it still hits:

simpler to dynamically create in my application.

(Also, your attempt was not only reasonable, it's actually close to what is in the ANSI Standards - might be worth your while voting on this connect issue)

It is possible to do multiple IN statements, this can be achieved by:

 SELECT *
 FROM Distributors
 WHERE CITY IN ('SPRINGFIELD', 'HOUSTON')
 AND STATE IN ('OH', 'MO', 'TX')

However it seems you want to filter using OR

 SELECT *
 FROM Distributors
 WHERE (City = 'Houston' AND State = 'TX') OR
 (City = 'Springfield' AND State = 'OH') OR
 (City = 'Springfield' AND State = 'MO')

Here is an answer, not pretty but it works:

SELECT *
FROM Distributors d
  INNER JOIN (SELECT 
                'Springfield' AS city
                ,'OH' AS state
              UNION 
              SELECT
                'Springfield'
                ,'MO'
              UNION
              SELECT 
                'Houston'
                ,'TX') x
WHERE d.city = x.city
  AND d.state = x.State

This construct is not supported. However you could write this in a slightly different way to the other suggestions:

SELECT <column list>
FROM dbo.Distributors
WHERE (City = 'Springfield' AND State IN ('OH', 'MO'))
   OR (City = 'Houston' AND State = 'TX');
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top