有条理地遍历列

时间:2017-06-13 15:37:07

标签: sql sql-server sql-server-2008 tsql

我已经整理了一个小型数据库,以便跟踪我和我的一些同事在足球赛季期间的一些累积投注。现在我需要编写一个函数来计算每个选择的奖金。关键表是选择函数的关键字段为odds和result_id,其中result_id为1是胜利。赌注存储在赌注表中。下面是选择表,其中有两个bet_id 1的获胜者,因此得到的等式将是((@stake * 1.40)* 1.40)。有没有办法使用游标或基于集合的方法来生成此值?

bet_id  punter_id   team_id odds    result_id   ground_id
1       1           24      1.40    1           1
1       1           48      1.60    2           1
1       1           89      1.60    2           1
1       2           8       1.40    1           1
1       2           11      1.60    2           1
1       2           107     1.60    2           1

2 个答案:

答案 0 :(得分:0)

假设您加入bet_id

CREATE TABLE bet (bet_id int NOT NULL PRIMARY KEY, 
                  stake float NOT NULL); -- or some floating point number type

要乘以一个组,我们使用以下关系:

log( a * b * c ) = log(a) + log(b) + log(c)

因此用于乘法

a * b * c = exp( log( a * b * c ) ) = exp( sum( log(.) ) )

计算因子

bet_id | odds_factor 
1      | 1.40 * 1.40 = 1.96

我们在此查询中使用公用表表达式CTE

WITH factor( bet_id, odds_factor ) AS 
  ( SELECT bet_id, exp( sum( log( odds ) ) ) 
    FROM selection 
    WHERE result_id = 1  -- only winning odds in the grouping
    GROUP BY bet_id ) 
SELECT b.bet_id, 
       b.stake, 
       f.odds_factor, 
       b.stake * f.odds_factor AS "total_odds" 
FROM bet b
INNER JOIN factor f 
ON b.bet_id = f.bet_id 
-- ORDER BY b.bet_id -- optional ordering for readability

应该产生(未经测试)

bet_id | stake | odds_factor | total_odds 
1      | 10.0  | 1.96        | 19.6

答案 1 :(得分:0)

认为这很简单:

SELECT      B.BET_ID, 
            S.PUNTER_ID,
            ((B.stake * S.odds) * S.odds)
FROM        BET         AS B
INNER JOIN  SELECTION   AS S ON B.Bet_id = S.Bet_id
WHERE       S.result_id = 1