首页 > 解决方案 > 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 服务器。

标签: sqlsql-serverpivotleft-joinaggregate-functions

解决方案


您可以使用条件聚合:

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

推荐阅读