我正在尝试从多个表中获取数据但不确定如何执行此操作。下面是我正在使用的查询,但它不起作用。请建议。
SELECT DISTINCT
VWL.Type, VWL.ID AS CompanyID,VWL.Name
FROM dbo.LeadList_New AS VWL
LEFT OUTER JOIN
CASE VWL.Type WHEN 'COMPANY' THEN
CRMCompanyEmailAddress AS CE ON VWL.ID=CE.CRMCompanyID
WHEN 'PERSON' THEN
PersonEmailAddress AS PE ON VWL.ID=PE.PersonID
END
答案 0 :(得分:6)
您无法使用CASE
加入表格,也许您想要这样:
SELECT DISTINCT VWL.Type, VWL.ID AS CompanyID, VWL.Name,
CASE WHEN VWL.type = 'COMPANY'
THEN CE.Name
ELSE PE.Name
END AS EntityName
FROM dbo.leadlist_new AS VWL
LEFT OUTER JOIN crmcompanyemailaddress AS CE
ON VWL.id = CE.crmcompanyid
LEFT OUTER JOIN personemailaddress AS PE
ON VWL.id = PE.personid
答案 1 :(得分:3)
您应该将CASE语句移动到SELECT主体中:
SELECT DISTINCT
VWL.Type, VWL.ID AS CompanyID,VWL.Name
case VWL.Type
when 'COMPANY' then CE.Address
when 'PERSON' then PE.Address
end
FROM dbo.LeadList_New AS VWL
LEFT OUTER JOIN CRMCompanyEmailAddress as CE on VWL.ID=CE.CRMCompanyID
LEFT OUTER JOIN PersonEmailAddress as PE on VWL.ID=PE.PersonID
或者只是UNION公司和个人的两个陈述
SELECT VWL.Type, VWL.ID AS CompanyID,VWL.Name,CE.Address as Address
FROM dbo.LeadList_New AS VWL
LEFT OUTER JOIN CRMCompanyEmailAddress as CE on VWL.ID=CE.CRMCompanyID
WHERE VWL.Type='COMPANY'
UNION
SELECT VWL.Type, VWL.ID AS CompanyID,VWL.Name,PE.Address as Address
FROM dbo.LeadList_New AS VWL
LEFT OUTER JOIN PersonEmailAddress as PE on VWL.ID=PE.PersonID
WHERE VWL.Type='PERSON'