如何选择满足特定聚合属性的所有值?

huangapple go评论66阅读模式
英文:

How do I select all values which satisfy certain aggregate properties?

问题

我有一个名为"Customers"的表,包括以下内容:

  1. CustomerName
  2. Country
  3. City

我尝试列出所有来自至少有两名顾客的城市的顾客姓名。

这是我的初始尝试:

SELECT CustomerName, City
FROM Customers
GROUP BY City
HAVING COUNT(City) > 1

这是我得到的结果:

CustomerName City
Person A New York
Person C Los Angeles

在这里,Person A是来自纽约的人,出现在表格的顶部,类似于Person B。但是,我想要的是列出所有来自纽约和洛杉矶的顾客。

当我尝试:

SELECT COUNT(CustomerName), City
FROM Customers
GROUP BY City
HAVING COUNT(City) > 1

我得到了以下结果:

COUNT(CustomerName) City
3 New York
5 Los Angeles

这意味着代码是正常工作的,只是我的原始代码只显示了纽约和洛杉矶的顶部一个人。我该如何解决这个问题?

英文:

Say, I have a table (named "Customers") which consists of:

  1. CustomerName
  2. Country
  3. City

I am trying to list the names of all customers from cities where there are at least two customers.

This is my initial attempt:

SELECT CustomerName, City
FROM Customers
GROUP BY City
HAVING COUNT(City) > 1

This is the result that I got:

CustomerName City
Person A New York
Person C Los Angeles

Here, Person A is a person from NY who appears on the top of the table and similar for Person B. However, what I wanted was the listing of all customers from New York and LA.

When I tried:

SELECT COUNT(CustomerName), City
FROM Customers
GROUP BY City
HAVING COUNT(City) > 1

I had

COUNT(CustomerName) City
3 New York
5 Los Angeles

This means that the code is working properly, except that my original code only displays a person on top of the table from NY and LA. How do I resolve this issue?

答案1

得分: 0

我已经将选择部分中的城市移除,因为您说您只想要客户名称。

SELECT a.CustomerName
FROM Customers a
WHERE (
    SELECT COUNT(b.CustomerName)
    FROM Customers b
    WHERE b.City = a.City
) > 1
ORDER BY a.CustomerName
英文:

How about this? I've taken the city out of the select part since you said you just wanted customer names.

SELECT a.CustomerName
FROM Customers a
WHERE (
    SELECT COUNT(b.CustomerName)
    FROM Customers b
    WHERE b.City = a.City
) > 1
ORDER BY a.CustomerName

答案2

得分: 0

选择具有超过1名客户的城市,并使用该列表来选择客户:

SELECT cst.CustomerName
FROM Customers cst
WHERE Cst.City in (
    -- 所有至少有两名客户的城市
    SELECT CstGE2.City
    FROM Customers CstGE2
    GROUP BY CstGE2.City
    HAVING count(*) >= 2
)
英文:

Get cities with more than 1 customer in a subquery, and use that list to select the customers:

SELECT cst.CustomerName
FROM Customers cst
WHERE Cst.City in (
    -- All cities where there are at least two customers
    SELECT CstGE2.City
    FROM Customers CstGE2
    GROUP BY CstGE2.City
    HAVING count(*) >= 2
)

huangapple
  • 本文由 发表于 2023年1月9日 03:54:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75050833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定