如何查找同一列仅具有相同另一列的行
How to find rows where the same column has only the same another column
假设以下 table:
Name Age Occupation
Alex 20 Student
Alex 20 Seller
Alex 20 Minister
Liza 19 Student
Liza 20 Volunteer
Liza 21 HR partner
我想查找年龄列中只有(且只有)20 的姓名。所以从这个 table 我想得到所有 "Alex" 行并且根本没有 "Liza" 行。
谢谢!
您需要使用 Group By
和 Having
子句。试试这个
select Name
from table
group by Name
having count(case when Age = 20 then 1 end) = count(*)
count(case when Age = 20 then 1 end)
仅在 age = 20
时才计数,如果它等于总计数,则该名称只有 20
作为年龄。
一种方法是使用 NOT IN()
:
SELECT Name, Age, Occupation
FROM YourTable
WHERE Age = 20
AND Name NOT IN (SELECT Name FROM YourTable WHERE Age <> 20)
另一种方式:
select Name
from table
group by Name
having min(Age) = 20 and max(Age) = 20
假设以下 table:
Name Age Occupation
Alex 20 Student
Alex 20 Seller
Alex 20 Minister
Liza 19 Student
Liza 20 Volunteer
Liza 21 HR partner
我想查找年龄列中只有(且只有)20 的姓名。所以从这个 table 我想得到所有 "Alex" 行并且根本没有 "Liza" 行。 谢谢!
您需要使用 Group By
和 Having
子句。试试这个
select Name
from table
group by Name
having count(case when Age = 20 then 1 end) = count(*)
count(case when Age = 20 then 1 end)
仅在 age = 20
时才计数,如果它等于总计数,则该名称只有 20
作为年龄。
一种方法是使用 NOT IN()
:
SELECT Name, Age, Occupation
FROM YourTable
WHERE Age = 20
AND Name NOT IN (SELECT Name FROM YourTable WHERE Age <> 20)
另一种方式:
select Name
from table
group by Name
having min(Age) = 20 and max(Age) = 20