SQL Server : inserting Player vs Player names in to new table from tblEntrants

标签 sql sql-server

我有一个表tblEntrants,它是台球玩家的列表。我想为它们绘制灯具,因此我需要将列表的上半部分复制到 tblFixtures 中,然后将它们与列表的下半部分进行播放。

tblFixtures 有 3 列:player1、player2 和 compID。

这是我到目前为止所拥有的:

INSERT INTO tblFixtures (player1, compID)
    SELECT TOP (50) PERCENT 
        accountID, compID 
    FROM 
        tblEntrants
    WHERE 
        paid = 'y'  AND compID = @compID 
    ORDER BY 
        accountID ASC

INSERT INTO tblFixtures (player2)
    SELECT TOP (50) PERCENT accountID 
    FROM tblEntrants
    WHERE paid = 'y' AND compID = @compID 
    ORDER BY accountID DESC

但这就是这样做的......

Player1   Player 2   CompID
---------------------------
Bob     v null       {Guid}
Bill    v null       {Guid}
Ben     v null       {Guid}
null    v Matt       {Guid}
null    v Mick       {Guid}
null    v Mark       {Guid}

我需要调整上面的代码,将下半部分的玩家添加到上半部分玩家所在的 Player2 列中。像这样..

Player1   Player 2   CompID
---------------------------
Bob     v Matt       {Guid}
Bill    v Mick       {Guid}
Ben     v Mark       {Guid}

感谢任何帮助

最佳答案

INSERT into tblFixtures (player1, compID, player2)
SELECt top1.accountID,compID, least1.accountID
  FROM
    (SELECT accountID, compID , 
            ROW_NUMBER() OVER (ORDER BY accountID) rn
       FROM tblEntrants
      WHERE paid = 'y'  AND compID=@compID) top1,

    (SELECT accountID ,
            ROW_NUMBER() OVER (ORDER BY accountID desc) rn
       FROM tblEntrants
    WHERE paid = 'y'  AND compID=@compID ) least1
WHERE top1.rn = least1.rn
  AND top1.rn <= (select round(count(*)/2,0) from tblEntrants where paid = 'y' and compID=@compID )

关于SQL Server : inserting Player vs Player names in to new table from tblEntrants,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46840984/

相关文章:

asp.net - 在任务关键型数据库驱动的 Web 应用程序中,异常处理的最佳范例或设计模式是什么?

sql-server - 在 SQL Select 语句中读取 XML 值

SQL内连接与左连接问题

sql - 将一张表中的数据插入到多张表中

sql - 有线SQL查询

mysql - 使用mysql在表的最后一行显示总和

node.js - 使用 sequelize-automate 时出错 "ConnectionError [SequelizeConnectionError]: Failed to connect to localhost:1443 - Could not connect (sequence)"

sql - 如何加快聚集列的大规模更新?

sql - 使用选择和参数执行 DB2 插入

php - 从 mysql 结果创建一个 id 数组