我有一个表,代表任何一天客户的多次交易。如果每位客户的三分之二或更多的交易是现金而不是信用卡,我需要退还每位客户的所有交易。
在下面的示例中,我要退回所有客户的1、4笔交易,因为他们是唯一拥有三分之二或更多交易现金的客户:
+ ---------------- + ------------- + ----------------- + ------------------ + | 交易编号| 客户编号| 交易类型| 交易价值| + ---------------- + ------------- + ----------------- + ------------------ + | 1 | 1 | 现金| 11 | | 2 | 1 | 卡 12 | | 3 | 1 | 现金| 13 | | 4 | 2 | 现金| 14 | | 5 | 2 | 卡 15 | | 6 | 3 | 现金| 15 | | 7 | 3 | 卡 11 | | 8 | 3 | 现金| 12 | | 9 | 3 | 卡 13 | | 10 | 4 | 现金| 14 | | 11 | 4 | 现金| 15 | | 12 | 4 | 现金| 15 | + ---------------- + ------------- + ----------------- + ------------------ +
这似乎适用于示例数据:
declare @t table (TranID int not null,CustomerNum int not null,
TranType varchar(17) not null,TranValue decimal(18,0) not null)
insert into @t(TranID,CustomerNum,TranType,TranValue) values
( 1,1,'Cash',11), ( 2,1,'Card',12), ( 3,1,'Cash',13),
( 4,2,'Cash',14), ( 5,2,'Card',15),
( 6,3,'Cash',15), ( 7,3,'Card',11), ( 8,3,'Cash',12), ( 9,3,'Card',13),
(10,4,'Cash',14), (11,4,'Cash',15), (12,4,'Cash',15)
;With Counted as (
select *,
COUNT(*) OVER (PARTITION BY CustomerNum) as cnt,
SUM(CASE WHEN TranType='Cash' THEN 1 ELSE 0 END)
OVER (PARTITION BY CustomerNum) as cashcnt
from @t
)
select * from Counted
where cashcnt * 3 >= cnt * 2
最后,我进行了简单乘法运算,以将所有数学保持为整数,而不必考虑浮点数/小数和2/3的表示形式。
结果:
TranID CustomerNum TranType TranValue cnt cashcnt
----------- ----------- ----------------- ----------- ----------- -----------
1 1 Cash 11 3 2
2 1 Card 12 3 2
3 1 Cash 13 3 2
10 4 Cash 14 3 3
11 4 Cash 15 3 3
12 4 Cash 15 3 3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句