views:

21

answers:

2

I have table table

Car:

Id
Name
ProductionCountry

Containers :

ID (GUID)
CarId

I want to get containers, where are cars from different countries

So:

Cars:
1 BMW X5 DE
2 BMW X3 DE
3 AUDI A6 MX
4 AUDI A1 FR
5 VOLVO S40 FR

Containers
Guid1 1
Guid1 2
Guid1 3
Guid2 4
Guid2 5

So in result I get Guid1 because in this container are cars from different countries.

How to write query to get it?

+1  A: 

I think (I've no access to sql at the moment but I'm guessing at something like)

select id, count(productioncountry)
from (
       select distinct id, productioncountry 
       from container c inner join car on car.id = c.CarId) conts
group by id
having count(productioncountry) > 1
Preet Sangha
Hmm.. your query gives me id of containers which has more than one car. I want to have id of containeres which have another production country. So: query gives first container, it checks in table cars foreach car what is its production country. First car has De, second car DE, and ...third car in this container has MX and now I want code of this container. Next he checks second container. Firs car has been produced in France, second too, so I don't want id of this container. Etc...
I've updated my answer
Preet Sangha
+1  A: 

Question:

How to retrieve container which contain cars from different countries ?

Answer:

SELECT Containers.ID FROM Containers INNER JOIN Car ON Containers.CarId = Car.Id
GROUP BY Containers.ID
HAVING COUNT(DISTINCT ProductionCountry) > 1
GO

How it works ?

We join the tables cars on containers on the car unique identifier. This give us information about what countries identifier are in which containers

Guid1 DE
Guid1 DE
Guid1 MX
Guid2 FR
Guid2 FR

So we group the result by container id and count unique countries ids

Guid1 2
Guid2 1

On the last step we filter the result to have only those containers where the amount of countries is greater than one.

Guid1
Vash