查找具有匹配主键的两个表的最新日期

时间:2013-04-02 16:35:44

标签: sql

我有两个表格表,每个表格都有不同人的主键和每个类别中的联系日期。我正在尝试查找每个人的最新联系日期,无论其中的表格如何。例如:

CustomerService列:CustomerKey,DateContacted CustomerOutreach列:CustomerKey,DateContacted

而我只是想找到每个人的最新日期。

3 个答案:

答案 0 :(得分:3)

使用类似的东西。

您需要合并这两个表。你可以通过工会来做到这一点。将有重复项,但您只需按customerKey分组,然后找到Max DateContacted

SELECT * INTO #TEMP FROM (
SELECT 
    CustomerKey
    , DateContacted
FROM CustomerService CS
UNION
SELECT 
    CustomerKey
    , DateContacted
FROM CustomerOutreach CS
)


SELECT
    CustomerKey
    , MAX(DateContacted)
FROM #TEMP
GROUP BY
    CustomerKey

答案 1 :(得分:2)

在主键上加入表格并进行条件投影。

  Select cs.CustomerKey, 
         CASE WHEN cs.DateContacted  <= co.DateContacted   
                 THEN co.DateContacted  
                 ELSE cs.DateContacted END  
      from CustomerService cs inner join CustomerOutreach co
           on cs.CustomerKey = co.CustomerKey 

答案 2 :(得分:1)

我会做这样的事情。

Select b.customerKey, b.dateContacted
from (
  select a.customerKey, a.DateContacted, Row_Number() over (Partition by customerKey      order by DateContacted desc) as RN
  from (
    Select c.customerKey, 
     case when (s.DateContacted > o.dateContacted) then s.dateContacted else o.datecontacted end as DateContacted
    from Customer c
    left outer join customerService s on c.customerKey = s.customerKey
    left outer join customerOutreach o on c.customerKey = s.customerKey
    where s.customerKey is not null or o.customerKey is not null
  )a
)b
where b.RN = 1

如果两个表具有相同的最大DateContacted,则此解决方案应该注意防止出现重复的情况。

http://sqlfiddle.com/#!3/ca968/1