左加入额外信息
LEFT JOIN with EXTRA INFORMATION
我有2张桌子
表 1:户
Serial_no
Address
sn1
New York
sn2
Maryland
sn3
France
表 2:市民
Serial_id
Fullname
Role
household_id
1
John
Head
sn1
2
Jane
Spouse
sn1
3
Johny
Son
sn1
4
Mike
Head
sn2
我希望输出是这样的:
Serial_no
Address
Total_count
Head
sn1
New York
3
John
sn2
Maryland
1
Mike
sn3
France
0
null
我被困在这里了。请帮忙。提前致谢!
您可以使用 group by
的条件聚合,如下所示:
架构和插入语句:
create table households(Serial_no varchar(10), Address varchar(50));
insert into households values('sn1', 'New York');
insert into households values('sn2', 'Maryland');
insert into households values('sn3', 'France');
create table citizens(Serial_id int, Fullname varchar(50), Role varchar(10), household_id varchar(10));
insert into citizens values(1,'John', 'Head', 'sn1');
insert into citizens values(2,'Jane', 'Spouse', 'sn1');
insert into citizens values(3,'Johny', 'Son', 'sn1');
insert into citizens values(4,'Mike', 'Head', 'sn2');
查询:
select Serial_no,Address,count(c.household_id) Total_count,
max(case when Role='Head' then Fullname end) Head
from households h
left join citizens c
on h.Serial_no=c.household_id
group by Serial_no,Address
输出:
Serial_no
Address
Total_count
Head
sn1
New York
3
John
sn2
Maryland
1
Mike
sn3
France
0
null
db<>fiddle here
我有2张桌子
表 1:户
Serial_no | Address |
---|---|
sn1 | New York |
sn2 | Maryland |
sn3 | France |
表 2:市民
Serial_id | Fullname | Role | household_id |
---|---|---|---|
1 | John | Head | sn1 |
2 | Jane | Spouse | sn1 |
3 | Johny | Son | sn1 |
4 | Mike | Head | sn2 |
我希望输出是这样的:
Serial_no | Address | Total_count | Head |
---|---|---|---|
sn1 | New York | 3 | John |
sn2 | Maryland | 1 | Mike |
sn3 | France | 0 | null |
我被困在这里了。请帮忙。提前致谢!
您可以使用 group by
的条件聚合,如下所示:
架构和插入语句:
create table households(Serial_no varchar(10), Address varchar(50));
insert into households values('sn1', 'New York');
insert into households values('sn2', 'Maryland');
insert into households values('sn3', 'France');
create table citizens(Serial_id int, Fullname varchar(50), Role varchar(10), household_id varchar(10));
insert into citizens values(1,'John', 'Head', 'sn1');
insert into citizens values(2,'Jane', 'Spouse', 'sn1');
insert into citizens values(3,'Johny', 'Son', 'sn1');
insert into citizens values(4,'Mike', 'Head', 'sn2');
查询:
select Serial_no,Address,count(c.household_id) Total_count,
max(case when Role='Head' then Fullname end) Head
from households h
left join citizens c
on h.Serial_no=c.household_id
group by Serial_no,Address
输出:
Serial_no | Address | Total_count | Head |
---|---|---|---|
sn1 | New York | 3 | John |
sn2 | Maryland | 1 | Mike |
sn3 | France | 0 | null |
db<>fiddle here