sql - 如何编写 SQL 以在一行中显示两列的不同值
问题描述
我有表a,b。表一
ID In
----------------
1 Mat1
1 Mat2
2 Mat1
3 Mat3
表b
ID Out
--------------
1 Mat4
2 Mat4
2 Mat5
3 Mat6
我想要一个像下面这样的结果。
ID In Out
------------------
1 Mat1 Mat4
1 Mat1
2 Mat1 Mat4
2 Mat5
3 Mat3 Mat6
我认为完全加入不能在某些行中创建空字段。也许我需要为此使用 Rownum?有什么帮助吗?谢谢。
解决方案
一种选择是用于row_number()
枚举行,然后full join
是结果。为此,您需要在每个表中都有一个列来对记录进行排序。我假设ordering_id
:
select id, a.in, b.out
from (
select a.*, row_number() over(partition by id order by ordering_id) rn
from tablea a
) a
full join (
select b.*, row_number() over(partition by id order by ordering_id) rn
from tableb b
) b using(id, rn)
并非所有数据库都支持full join
(并且并非所有数据库都支持using()
连接条件)。
一种更便携的方法是使用union all
:
select id, max(in) in, max(out) out
from (
select id, in, null out, row_number() over(partition by id order by ordering_id) rn
from tablea
union all
select id, null, out, row_number() over(partition by id order by ordering_id) rn
from tableb b
) x
group by id, rn
推荐阅读
- python - 从未传递给 __init__ 方法的类继承属性
- javascript - 为什么我的警报在 if() 中时没有弹出?
- python - The Osmnx python graph_to_gdfs sometimes returns a list in the name column, what's causing this?
- c# - 从 .NET Core 2.0 迁移到 3.1 后,jQuery.Ajax 调用返回“404 Not Found”
- node.js - 如何将节点中的请求发送到使用 grpc-web-proto 的端点?
- javascript - 在 AXIOS 调用 PHP 之后,对象数组变成字符串数组
- microservices - 3 层架构(单体?)与微服务
- c# - 无法在发布 WCF 请求 .NET C# 中接收“\”字符
- oauth - IdentityServer4:无法检索访问令牌,处理远程登录时遇到错误
- arrays - 如何从 API 解析 JSON