在单列中选择多个值的 Vanilla SQL
如果我有一个表,其中一列包含客户 ID,另一列包含时区,是否有一个简单的 SQL 语句可以选择具有不同时区值的所有客户 ID?换句话说,我想找到那些在纽约、芝加哥和旧金山设有办事处的客户,而不是那些只在一个或其他时区设有办事处的客户。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
DISTINCT 的使用很重要。
COUNT(TimeZone) 计算所有非空值,而不仅仅是不同值。所以它相当于 COUNT(*),除了 TimeZone 为空的地方。
换句话说,如果给定客户拥有三个办事处,但全部位于东部时区,则 COUNT(TimeZone) 将为 3,而 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.
丑陋但有效:
ugly, but effective: