开发者

Vanilla SQL that selects multiple values in single column

开发者 https://www.devze.com 2023-03-16 02:27 出处:网络
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

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.


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.


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


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
)
0

精彩评论

暂无评论...
验证码 换一张
取 消