我不会尝试想出一些聪明的(阅读复杂的)方法来尝试将您的更新塞进您当前的设计中,但会改变您的表格的设计。
BEGIN TRAN
CREATE TABLE Games (GameID INT PRIMARY KEY)
CREATE TABLE Players (PlayerID INT PRIMARY KEY)
CREATE TABLE PlayersGames (GameID INT, PlayerID INT, Position INT, conrti INT)
INSERT INTO Games VALUES (1), (2)
INSERT INTO Players VALUES (1), (2), (3), (4), (5)
INSERT INTO PlayersGames VALUES (1,1,1,0), (1,2,2,0), (1,3,3,0), (1,4,4,0), (1,5,5,0), (2,2,1,0), (2,1,2,0), (2,5,3,0), (2,3,4,0), (2,4,5,0)
ROLLBACK TRAN
现在你UPDATE
可以像
UPDATE PlayersGames SET contri = @YourValue WHERE PlayerID = 4 AND GameID = 1
编辑
为了完整起见,整个脚本,包括根据您的问题显示结果可能如下所示
BEGIN TRAN
CREATE TABLE dbo.Games (GameID INT PRIMARY KEY)
CREATE TABLE dbo.Players (PlayerID INT PRIMARY KEY)
CREATE TABLE dbo.PlayersGames (GameID INT, PlayerID INT, Position INT, contri INT)
ALTER TABLE dbo.PlayersGames ADD CONSTRAINT FK_PLAYERSGAMES_PLAYERS FOREIGN KEY (PlayerID) REFERENCES dbo.Players(PlayerID)
ALTER TABLE dbo.PlayersGames ADD CONSTRAINT FK_PLAYERSGAMES_GAMES FOREIGN KEY (GameID) REFERENCES dbo.Games(GameID)
INSERT INTO Games VALUES (1), (2)
INSERT INTO Players VALUES (1), (2), (3), (4), (5)
INSERT INTO PlayersGames VALUES (1,1,1,0), (1,2,2,3), (1,3,3,0), (1,4,4,0), (1,5,5,0), (2,2,1,0), (2,1,2,0), (2,5,3,0), (2,3,4,0), (2,4,5,0)
SELECT GameID
, Player1 = MIN(CASE WHEN Position = 1 THEN PlayerID ELSE NULL END)
, Player2 = MIN(CASE WHEN Position = 2 THEN PlayerID ELSE NULL END)
, Player3 = MIN(CASE WHEN Position = 3 THEN PlayerID ELSE NULL END)
, Player4 = MIN(CASE WHEN Position = 4 THEN PlayerID ELSE NULL END)
, Player5 = MIN(CASE WHEN Position = 5 THEN PlayerID ELSE NULL END)
, contri_P1 = MIN(CASE WHEN Position = 1 THEN contri ELSE NULL END)
, contri_P2 = MIN(CASE WHEN Position = 2 THEN contri ELSE NULL END)
, contri_P3 = MIN(CASE WHEN Position = 3 THEN contri ELSE NULL END)
, contri_P4 = MIN(CASE WHEN Position = 4 THEN contri ELSE NULL END)
, contri_P5 = MIN(CASE WHEN Position = 5 THEN contri ELSE NULL END)
FROM PlayersGames
GROUP BY
GameID
ROLLBACK TRAN