基于DateTime或CustMCId的最新数据

时间:2013-10-01 14:19:25

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

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

 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

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

1 个答案:

答案 0 :(得分: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;