如何以数学方式生成固定值的百分比

时间:2016-06-08 11:29:45

标签: sql sql-server

我正在发布只知道如何编写以下要求的代码:

我有一个球队名单,每支球队有20名球员。每个团队的名称由团队名称组成,即'FirstName'和'Player ...'为'Surname',其中增量编号(From'DumberID')出现在字符串'Player'之后。

我想要做的是对每支球队的20名球员说,必须在“位置”字段下输入以下位置:

  • GK(仅限2名球员(换句话说,10%的球员)
  • DF(仅限6名球员(换句话说,30%的球员)
  • MF(仅限6名球员(换句话说,30%的球员)
  • FW(仅限6名球员(换句话说,30%的球员)

然后根据他们的位置,根据他们在1 - 100之间的“位置”为每个玩家执行随机的“玩家权衡”

  • GK - 前3%的球员加权(0-3)
  • DF - 4% - 玩家权重的30%(4 - 30)
  • MF - 31% - 玩家权重的60%(31 - 60)
  • FW - 61% - 99%的球员加权(61 - 99) 我可以帮忙编码吗? 以下是我现在所拥有的内容及其产生的输出:

      CREATE PROCEDURE [dbo].[Player_CreateWholeTeam]
        @TeamID INT
    
    AS
    SET NOCOUNT ON
    BEGIN
    
    
    
        INSERT INTO dbo.Player (FirstName, Surname, TeamID)
        SELECT TeamName AS FirstName, 'Player' + cast(NumberID AS VARCHAR (10)) AS Surname, @TeamID
            FROM dbo.Team t
            CROSS JOIN dbo.Number n
            WHERE TeamID = @TeamID
            AND n.NumberID <= 20
    
    -- abs(checksum(newid()) % 99) + 1 AS PlayerWeighting,
    
    select * from dbo.Player
    
    END
    

    输出(&#39;播放器&#39;表):

enter image description here

1 个答案:

答案 0 :(得分:1)

只需使用Searched CASE expression代替SELECT中的其余两列:

CASE
  WHEN n.NumberId BETWEEN 1 AND 2 THEN 'GK'
  WHEN n.NumberId BETWEEN 3 AND 8 THEN 'DF'
  ...
END AS Position,
CASE
  WHEN n.NumberId BETWEEN 1 AND 2 THEN ABS(CHECKSUM(NEWID())) % 4
  WHEN n.NumberId BETWEEN 3 AND 8 THEN ABS(CHECKSUM(NEWID())) % 27 + 4
  ...
END AS PlayerWeigthing,

如果你还想随机化玩家数字,你必须为你的数字创建一个随机映射,如下所示:

DECLARE @RNumber AS TABLE(n int IDENTITY(1,1), rn INT)

INSERT @RNumber 
  SELECT NumberID as rn FROM dbo.Number
    WHERE NumberID <= 20
    ORDER BY CHECKSUM(NEWID())

然后,您可以加入该号码而非原始号码表,并根据需要使用nrn