2

I have a table of cars where each car belongs to a company. In another table I have a list of company locations by city.

I want to select all cars from the cars table whose company has locations on all cities passed into the stored procedure, otherwise exclude those cars all together even if it falls short of one city.

So, I've tried something like:

select id, cartype from cars where companyid in 
(
  select id from locations where cityid in 
  (
     select id from cities
  )
)

This doesn't work as it obviously satisfies the condition if ANY of the cities are in the list, not all of them.

It sounds like a group by count, but can't make it work with what I tried.

I"m using MS SQL 2005

Hitesh
  • 3,449
  • 8
  • 39
  • 57
IIS7 Rewrite
  • 779
  • 3
  • 16
  • 31

3 Answers3

2

One example:

select id, cartype from cars c
where ( select count(1) from cities where id in (...))
    = ( select count(distinct cityid)
        from locations 
        where c.companyid = locations.id and cityid in (...) )
Lennart - Slava Ukraini
  • 6,936
  • 1
  • 20
  • 32
0

Maybe try counting all the cities, and then select the car if the company has the same number of distinct location cities are there are total cities.

SELECT id, cartype FROM cars
WHERE
    --Subquery to find the number of locations belonging to car's company
    (SELECT count(distinct cities.id) FROM cities
    INNER JOIN locations on locations.cityid = cities.id
    WHERE locations.companyId = cars.companyId)
    =
    --Subquery to find the total number of locations
    (SELECT count(distinct cities.id) FROM cities)

I haven't tested this, and it may not be the most efficient query, but I think this might work.

slevin
  • 308
  • 1
  • 8
0

Try this

SELECT e.* 
FROM cars e
WHERE NOT EXISTS (
    SELECT 1 
    FROM Cities p
    WHERE p.location = e.Location
)
Jaynesh Shah
  • 158
  • 1
  • 1
  • 14