简体   繁体   English

在单列中选择多个值的香草 SQL

[英]Vanilla SQL that selects multiple values in single column

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?如果我有一张表,其中一列中有客户 ID,另一列有时区,是否有一个普通的 SQL 语句可以 select 所有具有不同时区值的客户 ID? 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. DISTINCT 的使用很重要。

COUNT(TimeZone) counts all non-null values, not just distinct values. COUNT(TimeZone) 计算所有非空值,而不仅仅是不同的值。 So it's equivalent to COUNT(*) except where TimeZone is null.所以它等价于 COUNT(*),除了 TimeZone 是 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.换句话说,如果给定客户有三个办事处,但都在东部时区,则 COUNT(TimeZone) 将为 3,而 COUNT(DISTINCT TimeZone) 将为 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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM