我正在使用SQL Server 2012,我有两个表Prospects
和ProspectContact
,其中包含以下示例数据:
ProspectID ProspectName ProspectAdd
-----------------------------------------------
1 ABC Company India
2 XYZ Company UAE
3 PQR Company KSA
4 JKL Company INDIA
ProspectContacts 表:
ProspectID CName CAdd CDesignation Email
---------------------------------------------------------------------------
1 Mr Sagar India Manager sagar@gmail.com
1 Mr Saurabh India Manager Saurabh@gmail.com
2 Mr Swami UAE Director swami@gmail.com
2 Mr .ABC UAE Engg abc@gmail.com
3 Mr PQR KSA Manager pqr@gmail.com
4 Mr XYZ INDIA Manager xyz@gmail.com
如果我通过以下查询在上述表格上应用左联接
SELECT
P.[PROSPECTNAME], P.[ADDRESS], PC.CONTACTPERSON, PC.EMAILID
FROM
[PROSPECTS] P
LEFT JOIN
[PROSPECTCONTACTS] PC ON P.PROSPECTID = PC.PROSPECTID
WHERE
P.USERID = @UserID
ORDER BY
CDATE DESC
我得到了这个结果集:
ProspectName Adress Name Email
---------------------------------------------------
ABC COMPANY INDIA Mr. Sagar sagar@gmail.com
ABC COMPANY INDIA Mr. Saurabh saurabh@gmail.com
我的预期结果集是这样的:
ProspectName Adress Name1 Email1 Name2 Email2
-----------------------------------------------------------------------------
ABC COMPANY INDIA Mr. Sagar sagar@gmail.com Mr.Saurabh saurabh@gmail.com
XYZ COMPNAY USA Mr.Swami swami@gmail.com Mr. ABC abc@gmail.com
PQR COMPANY KSA Mr.Pqr pqr@gmail.com NULL NULL
JKL COMPNAY INDIA Mr.XYZ xyz@gmail.com NULL NULL
答案 0 :(得分:0)
尝试这样的事情:
SELECT P.[PROSPECTNAME], P.[ADDRESS], PC.CONTACTPERSON, PC.EMAILID
FROM [PROSPECTCONTACTS] PC
LEFT JOIN [PROSPECTS] P
ON P.PROSPECTID=PC.PROSPECTID
WHERE P.USERID=@UserID ORDER BY CDATE Desc