1

If I have a table with customer IDs in one column and time zones in another, is there a plain SQL statement that can select all customer IDs that have different time zone values? In other words, I want to find those customers with offices in New York, Chicago, and San Francisco but not those who ONLY have an office in one or the other time zones.

bobs
  • 21,844
  • 12
  • 67
  • 78
phileas fogg
  • 1,905
  • 7
  • 28
  • 43

3 Answers3

3
SELECT Customer
FROM MyTable
GROUP BY Customer
HAVING COUNT(DISTINCT TimeZone) > 1

The use of DISTINCT is important.

COUNT(TimeZone) counts all non-null values, not just distinct values. So it's equivalent to COUNT(*) except where TimeZone is null.

In other words, if a given customer has three offices, but all are in the Eastern timezone, COUNT(TimeZone) will be 3, whereas COUNT(DISTINCT TimeZone) will be 1.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
1
SELECT Customer
FROM MyTable
GROUP BY Customer
HAVING COUNT(DISTINCT TimeZone) > 1
JNK
  • 63,321
  • 15
  • 122
  • 138
0

ugly, but effective:

select CustomerID
where  CustomerID in 
(
select customerID from
     (select distinct CustomerID
     from   table
     where  TimeZone in ('NY','CHI','SF')) t
having count(*) = 3
)
Phil
  • 179
  • 3