SQL查询:从两个单独的行连接两个字段

时间:2009-08-13 18:48:24

标签: sql left-join

我有以下两个表:

USER
FID  UID     VALUE
4    3       John
3    3    Doe
4    4       Jack
3    4       Russel

应该相当清楚FID 3 = Surname,FID 4 = Name。

DATEDATA
UID  DATE  
3    1234
4    4321

我想加入这两个表,以便我最终得到这样的结果:

UID  DATE  NAME   SURNAME
3    1234  John   Doe
4    4321  Jack   Russel

或......或者......

UID  DATE  FULLNAME
3    1234  John Doe
4    4321  Jack Russel

那里有SQL专家吗?

这是我到目前为止所做的:

SELECT UID, DATE, VALUE 
    from DATEDATA as D 
    left join USER as U 
    on U.uid = D.uid where fid = 3 OR fid = 4

但是这给了我这个:

UID  DATE  VALUE
3    1234  Doe
3    1234  John
4    4321  Russel
4    4321  Jack

任何?

4 个答案:

答案 0 :(得分:6)

SELECT D.UID, DATE, U.VALUE + ' ' + U2.Value as fullName
from DATEDATA as D 
left join USER as U on U.uid = D.uid and U.fid = 3
left join USER as U2 on U2.uid = D.uid and U2.fid = 4

虽然只要第一个或最后一个为NULL,这可能会给你一个NULL名称。在这种情况下,如果您可以接受用户在系统中只有一个名称或另一个名称的情况,您可能希望使用ISNULL将其中一个名称设为空字符串。

答案 1 :(得分:0)

SELECT A.UID, DATEDATA.DATE, A.VALUE, B.VALUE from DATEDATA, USER A, USER B 
WHERE A.UID = B.UID AND A.FID = 3 AND B.FID = 4 AND DATEDATA.UID = A.UID

答案 2 :(得分:0)

select 
  D.UID
, D.DATE
, isnull(U.VALUE, '') 'firstName'
, isnull(U2.VALUE, '') 'surName'
from
  DateData D
left join User U on U.uid = D.uid and U.fid = 3
left join User U2 on U2.uid = D.uid and U2.fid = 4

答案 3 :(得分:0)

您可以使用以下内容。它假设你总是有一个名字。如果你总是有一些字段并且它不是名字,那就把它作为第一个并重新调整连接。如果您从未保证价值,那么请告诉我们,我们将采取更难的解决方案。

select d.uid,COALESCE(d.date,'none entered'),COALESCE(frst.value,'') as NAME,COALESCE(lst.value,'') as SURNAME
from
user frst (NOLOCK)
left join user lst (NOLOCK) on lst.uid=frst.uid
left join datedata d (NOLOCK) on d.uid = frst.uid
where
frst.fid=4
AND lst.fid=3