SQL:避免重复并进行有条件的“分组”

时间:2018-12-05 02:04:46

标签: sql relational-database exacttarget salesforce-marketing-cloud

基于以下数据模式

Database Schema

我正在尝试建立一个查询,以返回系统中所有帐户的最后机会的所有联系人角色。

但是,如果帐户有1个机会,且其特定字段(阶段)的价值(资金),则优先使用此机会,因为有时系统可能有机会,但资金阶段不一定是为帐户创建的最后机会。

因此,如果我可以在表中表示此表,则最终表将是6条记录,因为第一个客户机会在角色中有两次联系(在out场景中很常见):

Records from sql

我创建了以下sql,但这是不对的,它带来了重复的记录,而且我不知道如何获取最新版本并将该最新版本调整为有阶段资助的版本。

SELECT 
    Id,
    OpportunityId,
    OpporutniyName,
    OpporutniyStage,
    FirstName,
    LastName,
    Mobile,
    Useractive,
    Email,
    EmailOptOut,
    AccountName,
    AccOppotunityInProgress,
    AccTotalLoanPaid,
    AccTotalClosedLost,
    TotalOppsLoanFunded,
    AccountID
FROM (
    SELECT 
        con.Id AS [Id], 
        opp.Id AS [OpportunityId], 
        acc.Id AS [AccountID],
        opp.Name AS [OpporutniyName],
        opp.StageName AS [OpporutniyStage],
        con.FirstName AS [FirstName],
        con.LastName AS [LastName],
        con.MobilePhone AS [Mobile],
        con.Useractive__c AS [Useractive],
        con.Email AS [Email],
        con.HasOptedOutOfEmail AS [EmailOptOut],
        acc.Name AS [AccountName],
        acc.Total_Opportunities_in_Progress__c AS [AccOppotunityInProgress],
        acc.Total_Loan_Paid__c AS [AccTotalLoanPaid],
        acc.Total_Closed_Lost__c AS [AccTotalClosedLost],
        opp.Total_Opportunities_Loan_Funded__c AS [TotalOppsLoanFunded],
        row_number() over(partition by opp_con_role.ContactId,opp.Id order by opp.CreatedDate desc) AS RowNum    
    FROM [OpportunityContactRole_Salesforce] opp_con_role
    LEFT JOIN [Opportunity_Salesforce] opp
        ON   opp_con_role.OpportunityId = opp.Id 
    JOIN [Contact_Salesforce] con
        ON   opp_con_role.ContactId = con.Id  
    JOIN [account_Salesforce] acc
        ON   acc.Id = opp.AccountId    
    WHERE con.Email IS NOT NULL OR con.MobilePhone IS NOT NULL 
) sr 
WHERE sr.RowNum = 1

0 个答案:

没有答案