0

我有两张桌子。(MS SQL 服务器 2012)

表现

 PortfolioID PortfolioCode  Date        MarketValue
    1         Port1         12/31/12    100000
    2         Port2         12/31/12    200000
    3         Port3         12/31/12    300000

计费率

RateID  FromRate        ToRate      Rate
1       1               100000      1
2       100000.01       200000      0.99
3       2000000.01      300000      0.98
4       300000.01       400000      0.97

我想运行一个类似于 CASE 语句的查询,在该语句中,我说如果投资组合在特定日期的 MarketValue 介于费率表上各层内的各种值范围之间,则其市值乘以其各自的费率。(比率列代表百分比率)

例如

Port1 falls in the RateID 1 tier and is multiplied by 1    100,000 * 1% = 1000
Port2 falls in the RateID 2 tier and is multiplied by .99  200,000 * .99% = 1980
Port3 falls in the RateID 3 tier and is multiplied by .98  300,000 * .98% = 2940

我有大约 100 个这样的“案例”,并且正在考虑做这样的事情

SELECT COALESCE(
CASE WHEN condition1 THEN calculation1 ELSE NULL END,
CASE WHEN condition2 THEN calculation2 ELSE NULL END,
etc...
)

但我无法弄清楚逻辑或如何最好地连接这两个表来实现这一点。

4

2 回答 2

1

你想像这样加入他们:

select p.*, p.MarketValue * br.rate
from Performance p left outer join
     BillingRates br
     on p.MarketValue between br.[from] and br.[to]

这称为非等值连接。这种连接的性能通常比等连接的性能差。有一个索引[from], [to]会有所帮助。

此外,您不应使用 SQL 保留字作为列名。也就是说,“from”和“to”是不方便的名称。

如果可能没有匹配项,那么您可能想要:

select p.*, p.MarketValue * coalesce(br.rate, 1.0)

所以结果不是NULL

于 2013-06-24T02:12:52.303 回答
1

这就是你将如何去创建一个过程:

CREATE PROCEDURE Test @MarketValue int
AS
BEGIN

DECLARE @rate decimal;

SET @rate = (SELECT rate 
             FROM billingrates 
             WHERE @marketvalue > "from" AND @marketvalue < to)

--Add your calculation and return/output value here
--@rate * @marketvlaue

END
于 2013-06-24T02:19:12.493 回答