有条件的不同选择

时间:2019-02-19 03:43:04

标签: sql

我正在使用Select Distinct DatabaseID删除DatabaseID的重复项。但是,有些行的最后一列ContactEmail包含电子邮件地址,而大多数行则没有。

Select Distinct DatabaseID仅排除不包含ContactEmail的重复项,而包含contactEmail的行仍具有两个databaseID。具体来说,有两个相同的数据库,一个数据库包含联系人电子邮件,而另一个数据库则没有。

   Select Tbl.DatabaseID, Tbl.TradingAccount, Tbl.FundManager
     ,Case When Tbl2.Dept = 'Rates Confirmation' Then Tbl2.ContactEmail Else '' END AS ContactEmail
    From TblMaster_Account as Tbl
    JOIN tblMaster_AcctContact as Tbl2
    ON Tbl.DatabaseID = Tbl2.DatabseID

我还希望删除具有ContactEmail的重复项,以便没有ContactEmail的重复数据将与具有ContactEmail的重复项合并在一起

当前表如下:

enter image description here

我想要:

enter image description here

2 个答案:

答案 0 :(得分:1)

下面是查询-

SELECT Tbl.databaseid, 
       Tbl.tradingaccount, 
       Tbl.fundmanager, 
       Max(CASE 
             WHEN Tbl2.dept = 'Rates Confirmation' THEN Tbl2.contactemail 
             ELSE '' 
           END) AS ContactEmail 
FROM   tblmaster_account AS Tbl 
       JOIN tblmaster_acctcontact AS Tbl2 
         ON Tbl.databaseid = Tbl2.databseid 
GROUP  BY Tbl.databaseid, 
          Tbl.tradingaccount, 
          Tbl.fundmanager

如果您的数据库支持分析功能,那么

SELECT databaseid, 
       tradingaccount, 
       fundmanager, 
       contactemail 
FROM   ( 
                SELECT   tl.databaseid, 
                         tl.tradingaccount, 
                         tl.fundmanager, 
                         t2.contactemail, 
                         Row_number() OVER (partition BY tl.databaseid, tl.tradingaccount, tl.fundmanager ORDER BY
                         CASE 
                                  WHEN t2.dept='Rates Confirmation' THEN t2.contactemail 
                                  ELSE '' 
                         END) AS rnk 
                FROM     tblmaster_account t1 
                JOIN     tblmaster_acctcontact t2 
                ON       ( 
                                  tl.databaseid = t2.databseid;)) WHERE rnk=1

答案 1 :(得分:1)

您可以尝试使用条件汇总功能。

Select
   Tbl.DatabaseID, 
   Tbl.TradingAccount, 
   Tbl.FundManager,
   MAX(Case When Tbl2.Dept = 'Rates Confirmation' Then Tbl2.ContactEmail Else '' END)AS ContactEmail
From TblMaster_Account as Tbl
JOIN tblMaster_AcctContact as Tbl2
ON Tbl.DatabaseID = Tbl2.DatabseID
GROUP BY  
    Tbl.DatabaseID, 
   Tbl.TradingAccount, 
   Tbl.FundManager