每天都有一个销售收入表和另一个评级表,用于根据收入里程碑计算绩效
CREATE TABLE #Rating(
[Revenue] int NULL,
[Percentage] float NULL
) ON [PRIMARY]
insert into [#Rating] select 20000, 1.1
insert into [#Rating] select 30000, 1.2
insert into [#Rating] select 40000, 1.3
CREATE TABLE #Sales(
[Date] datetime,
[Revenue] int NULL
) ON [PRIMARY]
insert into #Sales select '2017-01-01', 7000
insert into #Sales select '2017-01-02', 22000
insert into #Sales select '2017-01-03', 33000
insert into #Sales select '2017-01-04', 46000
insert into #Sales select '2017-01-05', 50000
我们希望根据评级来评估销售业绩。例如,
如果收入达到20000里程碑,则表现=收入* 1.0
如果收入达到30000里程碑,则表现=收入* 1.1
所以最后的表现应该如下
Date, Revenue, Performance
'2017-01-01', 7000, 7000
'2017-01-02', 22000, 24200
'2017-01-03', 33000, 39600
'2017-01-04', 46000, 59800
'2017-01-05', 50000, 65000
我可以知道如何设置匹配的查询吗?感谢
[编辑修改措辞]
答案 0 :(得分:1)
实现此目的的两种最简单方法是使用select语句中的子查询或外部应用。例如:
SELECT S.[Date],
S.Revenue,
Performance = S.Revenue * COALESCE(R.Percentage, 1)
FROM #Sales S
OUTER APPLY (SELECT TOP 1 R.Percentage FROM #Rating AS R WHERE R.Revenue <= S.Revenue ORDER BY R.Revenue DESC) AS R;
或者...
MAX(R.Percentage)
注意:您可以使用TOP 1
代替ORDER BY R.Revenue DESC
(也不包括{{1}}),因为随着收入的增加,百分比不太可能会下降。
答案 1 :(得分:0)
试试这个:
Select S.Date
,S.Revenue
,( (Select Max(R.Percentage)
From Rating R
Where S.Revenue < R.Revenue)
* S.Revenue) as Performance
From Sales S
答案 2 :(得分:0)
首先获得绩效评级表,使每条记录具有范围和相应的评级。 然后根据性能范围加入销售数据并计算最终性能。
with
RangePerformance as
(
select lag(Revenue, 1, 0) over (order by Revenue) LowVal, Revenue HighVal, Percentage
from Rating
)
select sales.Date, sales.Revenue, sales.Revenue*RangePerformance.Percentage
from sales
join RangePerformance
on sales.Revenue between RangePerformance.LowVal and RangePerformance.HighVal
分解
select lag(Revenue, 1, 0) over (order by Revenue) LowVal, Revenue HighVal, Percentage
from Rating
将为您提供中间结果集:
0 20000 1.1
20000 30000 1.2
30000 40000 1.3
然后根据Sales Collection的Join条件将此结果集连接到Sales表,该条件属于上述集合中的任何范围。