I created the following tables:
create table people
(
ID varchar(10),
name varchar(35),
CONSTRAINT pk_ID PRIMARY KEY (ID)
);
create table numbers
(
code varchar(10),
ID varchar(10),
number numeric,
CONSTRAINT pk_code PRIMARY KEY (code)
);
I inserted the following datas:
insert into people(ID, name)
values('fdx1','Peter');
insert into people(ID, name)
values('fdx2','Alice');
insert into people(ID, name)
values('fdx3','Louis');
insert into numbers(code, ID, number)
values('001','fdx1',1);
insert into numbers(code, ID, number)
values('002','fdx1',1);
insert into numbers(code, ID, number)
values('003','fdx2',2);
insert into numbers(code, ID, number)
values('004','fdx2',3);
insert into numbers(code, ID, number)
values('005','fdx3',4);
insert into numbers(code, ID, number)
values('006','fdx3',4);
My problem is: how to select people that has the same number. For example "Peter" and "Louis".
By "same number" you mean that there is only one number in numbers
for the person. You can do this with group by
and having
:
select n.id
from numbers n
group by n.id
having min(number) = max(number);
Note: this doesn't take NULL
into account. Your question doesn't specify what to do if one of the values is NULL
.
If I understand correctly you want to see out of the 2 rows for each user in numbers who has the same number twice? If so you could do.
SELECT p.ID, p.name, p.number, COUNT(DISTINCT n.id) as num
FROM people as p
INNER JOIN numbers as n on n.ID = p.ID
GROUP BY p.ID, n.number
HAVING num > 1
The would return a list of people how have the same number in numbers more than once
In case this was not what you were looking for some other things you could do are:
To return a list of people for a specific number you could do the following
SELECT p.ID, p.name
FROM people as p
INNER JOIN numbers as n on n.ID = p.ID
WHERE n.number = [[X]]
You would replace [[X]] with the number eg 1 this would then return a list of people who are linked to number 1 in this case Peter
If you wanted a list of all people and their associated number you could do:
SELECT p.ID, p.name, n.number
FROM people as p
INNER JOIN numbers as n on n.ID = p.ID
ORDER BY n.number
This would return the users ID, Name and their associated number.
You could use this query:
select p.name, n.number, count(*) repeats
from people p
inner join numbers n on n.ID = p.ID
group by p.id, n.number
having count(*) > 1
This lists the names of the people who have a duplicate number. That number is included in the output, and the number of times it occurs.
Output:
| name | number | repeats |
|-------|--------|---------|
| Peter | 1 | 2 |
| Louis | 4 | 2 |
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.