具有复杂连接的sql查询以获取唯一记录列表

时间:2015-02-26 12:10:24

标签: c# sql sql-server-2008 tsql

我需要一个查询,通过应用以下案例选择具有正确cardId的客户表。

如果您有任何建议,请分享。

可能的情况是:

  1. 只找到一条记录 - 很简单,使用发现的Card_id
  2. 未找到任何记录 - 请留空
  3. 找到多条记录 - 使用以2000开头的Card_id(如果可用),否则选择具有最新创建日期的(在CustomerCards表中)
  4. 客户表:

    ID        CardID
    1         200132
    2         263987
    3         100789
    ..
    

    CustomerCards表

    CustomerId         CardID        CreatedOn
    1                  209890        12/11/2014
    1                  200132        12/12/2014 
    1                  100732        11/10/2014
    2                  168902        12/11/2014
    2                  263987        15/01/2015
    

    我从左连接开始:

    select ct.* from dbo.Customer ct
    left join dbo.CustomerCard cc
    on ct.id = cc.customerId
    

    之后有点卡住了。

1 个答案:

答案 0 :(得分:1)

一个开始

;with cte1 as
(
select cc.CustomerId, cc.CardID, cc.CreatedOn
  from dbo.CustomerCard cc
 group by cc.CustomerId, cc.CardID, cc.CreatedOn 
having count(*) = 1
), cte200 as
(
select cc.CustomerId, cc.CardID, max(cc.CreatedOn)
  from dbo.CustomerCard cc
 group by cc.CustomerId, cc.CardID 
 where cc.CardID like '2000%'
)
select cte1
union
select cte2000 
union 
select ct.ID, ct.CardID, '1/1/1900' as  CreatedOn
  from dbo.Customer ct
  left join dbo.CustomerCard cc
    on ct.id = cc.customerId
 where cc.customerId is null 
union 
select cc.ID, cc.CardID, max(cc.CreatedOn)
  from dbo.CustomerCard cc 
  left join cte1  
    on cte1.customerId    = cc.customerId
  left join cte2000  
    on cte2000.customerId = cc.customerId
 where cte1.customerId    is null 
   and cte2000.customerId is null
 group by cc.ID, cc.CardID