我有一张桌子可以为每场比赛选出20名球员(基于他们的位置)。我所做的是创建了一个名为'FixturePlayer'的新表,只需将PlayerID和FixtureID存储到表中即可。
然而,我不确定如何将pl.PlayerID和pl.FixtureID插入' PlayerFixture'因为我已经在调用一个表格。我该怎么办?
WITH pl AS (SELECT DISTINCT p.PlayerID
,p.Position
,CASE WHEN p.TeamID = 0 THEN 0
ELSE p.playerWeighting END AS playerWeighting
,ABS(CHECKSUM(NewID())) % 10 + 1 AS Form
,t.TeamID
FROM dbo.Fixture f
INNER JOIN dbo.League l ON f.LeagueID = l.LeagueID
INNER JOIN dbo.Team t ON l.LeagueID = t.LeagueID
INNER JOIN dbo.Player p ON t.TeamID = p.TeamID
WHERE f.WeekNumber = 1)
,po AS (SELECT *, ROW_NUMBER() OVER(PARTITION BY pl.TeamID, pl.Position ORDER BY NEWID()) AS Rnk FROM pl)
,total AS (SELECT TeamID
,SUM(playerWeighting) AS TeamWeight
,SUM((playerWeighting / 10) * Form + playerWeighting) AS FinalTeamWeight
FROM po
WHERE (po.Position = 'GK' and po.rnk = 1) OR
(po.Position = 'DF' and po.rnk <= 4) OR
(po.Position = 'MF' and po.rnk <= 4) OR
(po.Position = 'FW' and po.rnk <= 2)
GROUP BY po.TeamID
CREATE PROCEDURE [dbo].[MatchDay_Insert]
AS
SET NOCOUNT ON
BEGIN
SELECT [TeamID], [TeamWeight], [Form], [FinalTeamWeight]
FROM TeamWeighting
ORDER BY TeamID
select * from player
END
PlayerFixture:
CREATE TABLE [dbo].[PlayerFixture]
(
[FixtureID] INT NOT NULL PRIMARY KEY,
[PlayerID] INT NULL
)
答案 0 :(得分:0)
这个问题有点不清楚,但我想你实际上想知道如何两次使用相同的cte
?一旦将数据插入dbo.PlayerFixture
,一次用于选择数据?
我总是这样做是临时表
IF OBJECT_ID('tempdb..#TblName') IS NOT NULL
BEGIN
DROP TABLE #TblName
END
;WITH cte AS (
....cte definition
)
INSERT INTO #TblName (Col1,....)
SELECT
Col1
FROM
cte
INSERT INTO dbo.PlayerFixture (FixtureId, PlayerId)
SELECT
FixtureId
,PlayerId
FROM
#TblName
SELECT *
FROM
#TblName
如果您只是意味着如何从上面定义的teh 3 cte获取数据,只需在您的cte定义之后直接写INSERT INTO dbo.PlayerFixture SELECT
,尽管这看起来不像您想要的cte本身