1

我有一张表,其中不同的客户端分配给不同的 MC。像客户端(84)切换 MC 3 次。现在想获取Client=84的最新MC。我做这个查询

 select max(cstmrMC.CustMCId),cstmrMC.CustId,cstmrMC.MCID,cstmrMC.AssignDate 
    from CustomerMC cstmrMC
    where cstmrMC.CustId=84
    group by cstmrMC.CustMCId,cstmrMC.CustId,cstmrMC.MCID,cstmrMC.AssignDate 
    ORDER BY cstmrMC.CustMCId,cstmrMC.CustId,cstmrMC.MCID,cstmrMC.AssignDate 

显示了这个结果

CustMCId     CustId   MCID            AssignDate
52           84    18      2013-10-01 18:21:56.000
59           84     7      2013-09-09 16:10:06.000
80           84    19      2013-10-09 03:54:00.000
156          84    21      2013-11-11 00:00:00.000

现在我只想要这个

156          84    21      2013-11-11 00:00:00.000

我怎样才能得到这个结果????

4

1 回答 1

0

使用 row_number 函数对客户进行分区和排序,以便最近的 MCID(基于 AssignDate)在每个客户中排在第一位。

WITH cteCustomers AS (
    SELECT CustMCId, CustId, MCID, AssignDate,
           ROW_NUMBER() OVER(PARTITION BY CustId ORDER BY AssignDate DESC) AS RowNum
        FROM CustomerMC
)
SELECT CustMCId, CustId, MCID, AssignDate
    FROM cteCustomers
    WHERE RowNum = 1;
于 2013-10-01T14:25:00.773 回答