我有两个表:
表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语句将产生该结果?MS SQL Server。
您可以使用条件聚合:
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