2017-06-07 98 views
1

沒有爲每一天,另一臺用於評價其使用基於收入的里程碑來計算性能與收入的銷售表計算性能

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

不是很清楚你在這裏需要什麼,我會建議加入銷售與評級,但沒有一個明確的解釋'介於20000和30000之間'應該在這兩個表之間。 –

+0

評級表是指里程碑。如果收入達到20000里程碑,性能=收入* 1.1。如果收入達到30000,則表現=收入* 1.2 – user2434918

回答

1

兩個最簡單的方式來實現這一目標是在你的SELECT語句子查詢或外部應用。例如:

SELECT S.[Date], 
     S.Revenue, 
     Performance = S.Revenue * COALESCE((SELECT TOP 1 R.Percentage FROM #Rating AS R WHERE R.Revenue <= S.Revenue ORDER BY R.Revenue DESC), 1) 
FROM #Sales S; 

或者......

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也一樣),因爲它是不可能的百分比會下降與收入增加。

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 
+0

由於收入較大,因此它不起作用並在4月1日和5月1日返回記錄空值 – user2434918

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 

然後根據屬於內的任何銷售收入的加盟條件加入這個結果集銷售表在上述範圍內。

+0

我無法測試它,因爲我沒有SQL Server 2012或更高版本。但是,如果收入超過40000美元,我認爲這是行不通的 – user2434918