选择值的最新更改

时间:2014-09-25 11:13:00

标签: sql-server-2008

我有桌子INTERESTRATE:

CustId   Dt   IntRt 
1      201401   1
1      201402   2
1      201403   2
1      201404   2
1      201405   3
2      201401   1
2      201402   1
2      201403   2
2      201404   2

我希望为每个CustID选择IntRt的最后更改日期以及更改内容。格式如Dt,原始IntRt,新IntRt。

所以select会返回:

CustID  Change
1       201405,2,3
2       201403,1,2

谢谢!

更新:

我尝试了类似的查询:

  

从INTERESTRATE中选择max(Dt),其中custID = CustID和IntRt<>   IntRt

我知道它显然是错误的,因为我比较相同的值所以它什么也不会返回,但我不知道该做些什么不同。

1 个答案:

答案 0 :(得分:1)

WITH cte AS (
  SELECT 
    rn = RANK() OVER (PARTITION BY CustID ORDER BY Dt DESC), *
  FROM INTERESTRATE
)
SELECT
  c1.CustId,
  c1.Dt,
  OriginalIntRt = (SELECT TOP 1 IntRt FROM cte c2 WHERE c1.CustId = c2.CustId AND c1.IntRt <> c2.IntRt ORDER BY dt DESC),
  c1.IntRt AS NewIntRt
FROM cte c1
WHERE c1.rn = 1