sql - SQL 语句从右表的多行中获取单个值作为输出中的列
问题描述
我有两张桌子:
表 A:
ID
1
2
3
4
5
表 B:
ID UDFNumber UDFValue
1 5 ID1sUDF5Value
1 6 ID1sUDF6Value
1 7 ID1sUDF7Value
1 8 ID1sUDF8Value
1 9 ID1sUDF9Value
2 5 ID2sUDF5Value
2 6 ID2sUDF6Value
2 7 ID2sUDF7Value
2 8 ID2sUDF8Value
2 9 ID2sUDF9Value
etc
我正在尝试仅将 UDF5 和 UDF9 的值作为表 A 中每一行的列输出。
我正在寻找的输出:
ID UDF5 UDF9
1 ID1sUDF5Value ID1sUDF9Value
2 ID2sUDF5Value ID2sUDF9Value
3 ID3sUDF5Value ID3sUDF9Value
等等
什么 join/sql 语句会产生该结果?微软 SQL 服务器。
解决方案
您可以使用条件聚合:
select id,
max(case when udfnumber = 5 then udfvalue end) as udf5,
max(case when udfnumber = 9 then udfvalue end) as udf9
from tableb
where udfnumber in (5, 9)
group by id
请注意,您不需要tablea
生成所需的结果 - 除非您想允许在tableb
. 如果是这样:
select a.id,
max(case when b.udfnumber = 5 then b.udfvalue end) as udf5,
max(case when b.udfnumber = 9 then b.udfvalue end) as udf9
from tablea a
left join tableb b on b.id = a.id and b.udfnumber in (5, 9)
group by a.id
最后:对于两个值,加入两次是一个可行的选择:
select a.id, b5.udfvalue as udf5, b9.udfvalue as udf9
from tablea a
left join tableb b5 on b5.id = a.id and b5.udfnumber = 5
left join tableb b9 on b9.id = a.id and b8.udfnumber = 9
推荐阅读
- node.js - npm run build 返回未找到模块:错误:无法在我的 NuxtJS 应用程序中的 docker 容器中解析
- java - android studio中的矢量路径数据
- powerbi - M Power Query 以 DAX 计算表为源
- windows - 詹金斯管道。curl 得到工作,但 post 没有
- html - 用作关键字的 JSON-LD 标签
- database - 密钥 1.0 不得包含“.” MongoDB Compass 中的错误
- r - 如何与 +inf 双重集成?
- excel - EntireRow.Insert 与上述单元格中的公式?
- php - Directus 获取用户/我?404响应
- python - import sklearn.model_selection.train_test_split vs import sklearn.model_selection as sm