1

我有两个表,每个表都有不同人的主键和每个类别中的联系日期。我试图找到每个人最近的联系日期,不管它在哪个表中。例如:

CustomerService 列:CustomerKey、DateContacted CustomerOutreach 列:CustomerKey、DateContacted

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

4

3 回答 3

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
于 2013-04-02T16:41:53.267 回答
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 
于 2013-04-02T16:50:22.697 回答
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

于 2013-04-02T16:57:09.960 回答