6

我正在尝试从多个表中获取数据,但不知道该怎么做。下面是我正在使用但它不起作用的查询。请建议。

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
4

2 回答 2

6

你不能用 a 加入表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 
于 2013-11-11T13:17:46.967 回答
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

或者只是联合两个公司和个人的声明

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'
于 2013-11-11T13:18:01.640 回答