SQL 语句从右侧 table 的多行中获取单个值作为输出中的列

SQL statement to get individual values from multiple rows from right table as columns in output

我有两个 table:

Table答:

ID  
1
2
3
4
5

Table乙:

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 的值作为 table A 中每一行的列。

我正在寻找的输出:

ID  UDF5            UDF9
1   ID1sUDF5Value   ID1sUDF9Value
2   ID2sUDF5Value   ID2sUDF9Value
3   ID3sUDF5Value   ID3sUDF9Value

等等

哪种 join/sql 语句会产生该结果? MS 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