我在银行工作。考虑到保持平衡,我们计划根据以下规则为客户提供一些要点:
Balance ---- Point(per 1000)
1000-5000 10
5000-10000 20
10000-20000 30
例如,某人的帐户中有20000,我们根据以下几点给他/她450点:
(5*10) + (5*20)+ (10*30)=450
我们大约有300万客户,我们应该计算他们的积分。
我们应该如何使用T-SQL编写此查询?
答案 0 :(得分:1)
有多种方法。这是一种方法:
select t.*,
((case when balance > 1000 and balance < 5000
then (balance - 1000) * 10.0 / 1000
else (5000 - 1000) * 10.0 / 1000
) +
(case when balance > 5000 and balance < 10000
then (balance - 5000) * 20.0 / 1000
else (10000 - 5000) * 20.0 / 1000
) +
(case when balance > 10000 and balance < 20000
then (balance - 10000) * 30.0 / 1000
else (20000 - 10000) * 30.0 / 1000
)
) as points
from t
答案 1 :(得分:1)
一种解决方法如下。关键假设是范围没有差距。 Working demo link
create table temp (Balance nvarchar(1000),Points int);
insert into temp values
('1000-5000' , 10)
,('5000-10000' ,20)
,('10000-20000',30);
create table Points(customerid int, balance int);
insert into Points values
(1,2637),(2,7888),(3,12782),(4,20000);
; with rangeTable as (
select
startrange=isnull
(lag(cast(right(Balance, len(Balance)-charindex('-',Balance)) as int)) over ( order by Points asc),0) ,
endrange=cast(right(Balance, len(Balance)-charindex('-',Balance)) as int) ,
Points
from temp
)
select sum(case when p.Balance >r.endrange then (r.endrange-r.startrange) else (p.Balance-r.startrange) end *r.Points)/1000,p.customerid,p.Balance from Points p cross join rangeTable r
where p.Balance >r.startrange
group by p.customerid,p.Balance
答案 2 :(得分:1)
我喜欢将层保持在表中。这消除了代码中的逻辑,并允许您在一个结构中支持多层。
示例
Declare @Tier table (TierGrp varchar(50),TierTitle varchar(50),TierR1 money,TierR2 money,Pnts int)
Insert Into @Tier values
('Sample','0 - 5' ,0 ,5000 ,10)
,('Sample','5 - 10' ,5000 ,10000 ,20)
,('Sample','10 - 20' ,10000 ,20000 ,30)
,('Sample','20 - 50' ,20000 ,50000 ,40)
,('Sample','50 - 100',50000 ,100000 ,50)
,('Sample','10+' ,100000,9999999,60)
Declare @YourTable table (ID int,RemainBalance money)
Insert Into @YourTable values
(1,20000)
,(2,15500)
,(3,30000)
Select A.ID
,A.RemainBalance
,Points = sum(floor(((IIF(RemainBalance>TierR2,TierR2,RemainBalance)-TierR1)/1000)) * Pnts )
From @YourTable A
Join @Tier B on TierGrp='Sample' and RemainBalance >=TierR1
Group By A.ID,A.RemainBalance
Order By A.ID
返回
ID RemainBalance Points
1 20000.00 450.00
2 15500.00 300.00
3 30000.00 850.00