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.
Asked
Active
Viewed 658 times
3 Answers
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 For the distinct. Also I updated my own answer to correct :) – JNK Jun 29 '11 at 20:15
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