我是SQL的新手,并且很难编写一个select查询来比较t个月到t-1个月的数据。这正是我想要的:
As_of_date Customer Status
1-Jan-11 1 A
1-Jan-11 2 A
1-Jan-11 3 A
1-Jan-11 4 A
1-Jan-11 5 A
1-Jan-11 6 A
1-Jan-11 7 A
1-Jan-11 8 A
1-Jan-11 9 A
1-Jan-11 10 A
1-Feb-11 1 A
1-Feb-11 2 A
1-Feb-11 3 A
1-Feb-11 4 B
1-Feb-11 5 A
1-Feb-11 6 A
1-Feb-11 7 B
1-Feb-11 8 A
1-Feb-11 9 A
1-Feb-11 10 A
1-Mar-11 1 A
1-Mar-11 2 B
1-Mar-11 3 A
1-Mar-11 4 B
1-Mar-11 5 B
1-Mar-11 6 A
1-Mar-11 7 B
1-Mar-11 8 A
1-Mar-11 9 B
1-Mar-11 10 A
我想每月为所有改变状态的客户提取资料。所以我的结果应该给我:
As of Date Customer Status
1-Jan-11 4 A
1-Feb-11 4 B
1-Jan-11 7 A
1-Feb-11 7 B
1-Feb-11 2 A
1-Mar-11 2 B
1-Feb-11 5 A
1-Mar-11 5 B
1-Feb-11 9 A
1-Mar-11 9 B
与上个月相比,这些客户已将其状态从A更改为B.请考虑只有2种状态。
感谢您的帮助
答案 0 :(得分:1)
此代码属于SQL Server,可以使用相同的逻辑。
With CTE as
(
select As_of_date
, Customer
,Status
,ROW_NUMBER() over (partition by Customer,Status order by Customer asc,As_of_date asc,Status asc) rN
from tblTest
)
select * from CTE as c
join CTE as c1 on c.Customer = c1.Customer
where c.rN = c1.rN
and c.Customer = c1.Customer
and c.Status <> c1.Status