SQL使用左连接删除重复结果

时间:2013-09-03 21:57:58

标签: sql group-by duplicates distinct

我有代码,如果从两个不同的表中提取信息,我得到重复。我在SELECT语句中尝试过DISTINCT,但是我收到很多错误“ntext数据类型不能被选为DISTINCT,因为它不具有可比性。”

所以我的下一次尝试是尝试GROUP BY,但是我收到错误“Column Person.Pers_FirstName在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

所以我的记录有多个关系字段,但这是一个问题,因为有些记录没有,一个或多个关系(选项是NULL,项目工程师,项目所有者或项目承包商)。当前代码仅显示NULL和项目工程师,但如果有其他两个记录,则排除它们。如果我包含其他关系描述,那么我会得到重复。

SELECT 
    RTRIM(ISNULL(Pers_FirstName, '')) + ' ' + RTRIM(ISNULL(Pers_LastName, '')) AS        Pers_FullName, 
    RTRIM(ISNULL(oppocomp.Comp_PhoneCountryCode, '')) + ' ' + RTRIM(ISNULL(oppocomp.Comp_PhoneAreaCode, '')) + ' ' + RTRIM(ISNULL(oppocomp.Comp_PhoneNumber, '')) AS Comp_PhoneFullNumber,
    RTRIM(ISNULL(oppocomp.Comp_FaxCountryCode, '')) + ' ' + RTRIM(ISNULL(oppocomp.Comp_FaxAreaCode, '')) + ' ' + RTRIM(ISNULL(oppocomp.Comp_FaxNumber, '')) AS Comp_FaxFullNumber, 
    RTRIM(ISNULL(Pers_PhoneCountryCode, '')) + ' ' + RTRIM(ISNULL(Pers_PhoneAreaCode, '')) + ' ' + RTRIM(ISNULL(Pers_PhoneNumber, '')) AS Pers_PhoneFullNumber, 
    RTRIM(ISNULL(Pers_FaxCountryCode, '')) + ' ' + RTRIM(ISNULL(Pers_FaxAreaCode, '')) + ' ' + RTRIM(ISNULL(Pers_FaxNumber, '')) AS Pers_FaxFullNumber, 
    Opportunity.*, oppocomp.Comp_Name, oppocomp.Comp_Territory, oppocomp.Comp_EmailAddress,
    oppocomp.Comp_CompanyId, oppocomp.Comp_SecTerr, oppocomp.Comp_CreatedBy,
    oppocomp.Comp_PrimaryUserID, Terr_Caption, Pers_Title, Pers_EmailAddress, Pers_SecTerr,
    Pers_CreatedBy, Pers_PersonId, Pers_PrimaryUserID, Chan_Description,
    oppocomp.Comp_ChannelID, (Oppo_Base_Currency.Curr_CurrencyID) AS Oppo_WeightedForecast_CID,
    Pers_ChannelID ((Oppo_Forecast / Oppo_Forecast_Currency.Curr_Rate) * Oppo_Certainty / 100) AS Oppo_WeightedForecast, 
    Oppo_PrimaryAccountId AS Acc_AccountId, rend_Notes, renl_description,
    relcomp.Comp_Name AS Rela_CompanyName 
FROM Opportunity 
LEFT JOIN Person ON Oppo_PrimaryPersonID = Pers_PersonID 
LEFT JOIN Company AS oppocomp ON Oppo_PrimaryCompanyID = Comp_CompanyId 
LEFT JOIN Territories ON Oppo_SecTerr = Terr_TerritoryId 
LEFT JOIN Channel ON Chan_ChannelId = Oppo_ChannelId 
LEFT JOIN RelatedEntityData ON Oppo_OpportunityId = rend_entity1id 
LEFT JOIN RelatedEntityLinks ON rend_relatedentitylinkid = REnL_RelatedEntityLinkID 
LEFT JOIN Company AS relcomp ON rend_entity2id = relcomp.Comp_CompanyId 
LEFT JOIN Currency Oppo_Forecast_Currency ON Oppo_Forecast_CID = Oppo_Forecast_Currency.Curr_CurrencyID 
LEFT JOIN Currency Oppo_Base_Currency 
     ON Oppo_Base_Currency.Curr_CurrencyID = (
                SELECT CAST(CAST(Parm_Value AS NCHAR) AS INTEGER) 
                  FROM Custom_SysParams
                 WHERE Parm_Name = 'BaseCurrency'
            ) 
WHERE Oppo_Deleted IS NULL
  AND (renl_description IS NULL OR renl_description = 'Project Engineer')

0 个答案:

没有答案