postgresql - Postgresql join same table
问题描述
I have table with fields:
line_id, point_address:
1 | Address1
1 | Address2
2 | Address1
2 | Address3
3 | Address2
3 | Address3
For result I need table with single row for each line_id and both point_address values line_id have in separate rows:
line_id,point_address_1,point_address_2:
1 | Address1 | Address2
2 | Address1 | Address3
3 | Address2 | Address3
I'm tried to create self join but what I got is 4 result for each line_id with all combinations of point_address fields. What is the best way to get single result
解决方案
Assuming there are only ever two addresses per distinct line_id
, you can work around by forcing an order on point_address
in the result table:
SELECT
l1.line_id, l1.point_address AS point_address1,
l2.point_address AS point_address2
FROM line_address l1 JOIN line_Address l2 ON l1.line_id = l2.line_id
WHERE l1.point_address < l2.point_address;
line_id point_address1 point_address2
---------- -------------- --------------
1 Address1 Address2
2 Address1 Address3
3 Address2 Address3
Note that this only works under the above assumption, hence if we add
INSERT INTO line_address (line_id, point_address) VALUES (3, 'Address4');
the select yields
line_id point_address1 point_address2
---------- -------------- --------------
1 Address1 Address2
2 Address1 Address3
3 Address2 Address3
3 Address2 Address4
3 Address3 Address4
Relational algebra does not take it kindly when you try to make rows into columns and vice versa.
推荐阅读
- node.js - 是否可以在 Node.js 中运行 Spring Boot REST API
- spring-boot - 具有用户角色和权限的 OAuth2 SSO
- r - Anaconda3 中的 R 语言:软件包已安装并位于 libpath 文件夹中。但它不能包括在内
- c++ - 是否可以在命令行中将输入参数传递给可执行文件
- java - 如何更新 JSON 文件中的几个字段并使用 Java 再次读取带有更新值的 JSON
- python - 如何从字符串中删除字典中的相应单词?
- python - 如何将 print(subprocess.checkout) 的输出存储到 Python 中的变量中?
- django - Django中的多个身份验证登录页面
- postgresql - 如何在 Postgres 中获得时间间隔的中位数?
- powershell - 在 PowerShell 中使用 Remove-PnPTenantSite 删除 SharePoint 站点不起作用