我有以下数据集(编辑。道歉)
设置
CREATE TABLE CustomerPoints
(
CustomerID INT,
[Date] Date,
Points INT
)
INSERT INTO CustomerPoints
VALUES
(1, '20150101', 500),
(1, '20150201', -400),
(1, '20151101', 300),
(1, '20151201', -400)
任何积分的积分都是积分,而积极积分则是兑换积分。由于FIFO(第一个概念中的第一个),在第二批花费的点数(-400)中,其中100个是从20150101(英国格式)获得的点数和从20151101获得的300点。
目标是为每位客户计算在x和y个月的收入中花费的点数。再次,谢谢你的帮助。
答案 0 :(得分:4)
你需要爆炸单个单位赚取和兑换的积分,然后将它们结合起来,这样每个获得的积分将与兑换积分相匹配。
对于这些匹配行中的每一行,计算从赚取到兑换所经过的月份,然后将其汇总。
对于FN_NUMBERS(n),它是一个计数表,请查看我上面链接的其他答案。
;with
p as (select * from CustomerPoints),
e as (select * from p where points>0),
r as (select * from p where points<0),
ex as (
select *, ROW_NUMBER() over (partition by CustomerID order by [date] ) rn
from e
join FN_NUMBERS(1000) on N<= e.points
),
rx as (
select *, ROW_NUMBER() over (partition by CustomerID order by [date] ) rn
from r
join FN_NUMBERS(1000) on N<= -r.points
),
j as (
select ex.CustomerID, DATEDIFF(month,ex.date, rx.date) mm
from ex
join rx on ex.CustomerID = rx.CustomerID and ex.rn = rx.rn and rx.date>ex.date
)
-- use this select to see points redeemed in current and past semester
select * from j join (select 0 s union all select 1 s ) p on j.mm >= (p.s*6)+(p.s) and j.mm < p.s*6+6 pivot (count(mm) for s in ([0],[2])) p order by 1, 2
-- use this select to see points redeemed with months detail
--select * from j pivot (count(mm) for mm in ([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) p order by 1
-- use this select to see points redeemed in rows per month
--select CustomerID, mm, COUNT(mm) PointsRedeemed from j group by CustomerID, mm order by 1
默认查询输出,0为0-6个月,1为7-12(以月为单位的兑换年龄)
CustomerID 0 1
1 700 100
第二个查询的输出,0..12是以月为单位的兑换年龄
CustomerID 0 1 2 3 4 5 6 7 8 9 10 11 12
1 0 700 0 0 0 0 0 0 0 0 0 100 0
第三次查询的输出,是以月为单位的兑换年龄
CustomerID mm PointsRedeemed
1 1 700
1 11 100
再见