【问题标题】:sql query with complicated join to get unique records list具有复杂连接的sql查询以获取唯一记录列表
【发布时间】:2015-02-26 12:10:24
【问题描述】:

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

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

可能的情况有:

  1. 只找到一条记录 - 很简单,使用找到的 Card_id
  2. 未找到记录 - 留空
  3. 找到多条记录 - 如果可用,请使用以 2000 开头的 Card_id,否则选择创建日期最近的一条(在 CustomerCards 表中)

客户表:

ID        CardID
1         200132
2         263987
3         100789
..

客户卡表

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

在那之后有点卡住了。

【问题讨论】:

  • 到目前为止你尝试过什么?向我们展示查询并解释它有什么问题!
  • 您可能需要查看 Case-When 以添加 if-then-else 类型的逻辑。

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


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多