左连接附加信息

发布于 2025-01-10 13:03:12 字数 2340 浏览 0 评论 0原文

我有 2 个表

table1: households

Serial_noAddress
sn1New York
sn2Maryland
sn3France

table2: citizens

Serial_idFullnameRolefamily_id
1JohnHeadsn1
2JaneSpousesn1
3JohnySonsn1
4MikeHeadsn2

我希望输出如下:

Serial_noAddressTotal_countHead
sn1New York3John
sn2Maryland1Mike
sn3France0null

我被困在这里了。请帮忙。提前致谢!

I have 2 tables

table1: households

Serial_noAddress
sn1New York
sn2Maryland
sn3France

table2: citizens

Serial_idFullnameRolehousehold_id
1JohnHeadsn1
2JaneSpousesn1
3JohnySonsn1
4MikeHeadsn2

I want the output to be like this:

Serial_noAddressTotal_countHead
sn1New York3John
sn2Maryland1Mike
sn3France0null

I'm stuck here. please help. Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

记忆之渊 2025-01-17 13:03:12

您可以使用 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_noAddressTotal_countHead
sn1New York3John
sn2Maryland1Mike
sn3France0null

db>>小提琴 此处

You can use conditional aggregation with group by like below:

Schema and insert statements:

 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');

Query:

 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 

Output:

Serial_noAddressTotal_countHead
sn1New York3John
sn2Maryland1Mike
sn3France0null

db<>fiddle here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文