我的原始代码将过去12个月中的所有交易都记录下来,然后比较前两笔最高的单笔交易。
如果该时间段内最高的单笔礼物比第二笔最大的单笔交易大两倍以上,请选择第二笔最高的单笔礼物。如果#1单笔最高礼物不超过两倍,则使用该礼物。
我发现我需要根据上述规则将最近的日期与前2个金额一起使用。如果我使用了过去的12个月,则无法获得所需的全部金额。
如何更改where语句以获取最新日期,而不是从当前日期算起的最近12个月。
输入值
account number, date, and transaction amount.
7428, 01262018, 2
7428, 12302018, 5
16988 02142016, 100
16988 01152016, 25
22450 04191971, 8
22450 08291971, 10
结果
AccountNumber Number Amount
------------------------------
7428 2 5.00
16988 2 25.00
22450 2 10.00
26997 2 10.00
27316 2 25.00
27365 2 25.00
28620 2 10.00
28951 2 10.00
29905 2 5.00
代码:
DECLARE @start_date date
DECLARE @end_date date
SET @start_date = DATEADD(YEAR, -1, GETDATE())
SET @end_date = GETDATE()
SELECT
AccountNumber,
COUNT(amount) as Number,
CASE
WHEN MAX(CASE WHEN row_num = 1 THEN amount END) > MAX(CASE WHEN row_num = 2 THEN amount END) * 2
THEN MAX(CASE WHEN row_num = 2 THEN amount END)
ELSE MAX(CASE WHEN row_num = 1 THEN amount END)
END AS Amount
FROM
(SELECT
*,
ROW_NUMBER() OVER(PARTITION BY AccountNumber ORDER BY amount DESC) AS row_num
FROM
dbo.[T01_TransactionMaster]
WHERE
date >= @start_date AND date < @end_date) AS tt
WHERE
row_num IN (1, 2)
AND amount > 0
-- AND AccountNumber = 301692
GROUP BY
AccountNumber