我有一张桌子scoresByMinute
,只要在足球场进球得分,就会显示得分线
matchID minute scoreline
1 24 10
1 53 20
1 81 21
2 7 01 ...
我希望创建一个新表,显示每个90分钟游戏的每分钟的得分线
matchID minute scoreline
1 1 00
1 2 00
...
1 23 00
1 24 01
1 25 01
...
1 89 21
1 90 21
2 1 00
等
我应该怎么做?
答案 0 :(得分:2)
;WITH scoresByMinute (matchID, minute, scoreline) AS (
SELECT 1, 24, '10' UNION ALL
SELECT 1, 53, '20' UNION ALL
SELECT 1, 81, '21' UNION ALL
SELECT 2, 7, '01'
),
maxMins AS (
SELECT
matchID,
maxMin = MAX(minute)
FROM scoresByMinute
GROUP BY matchID
),
allminutes AS (
SELECT
m.matchID,
minute = v.number,
scoreline = s.scoreline
FROM maxMins m
INNER JOIN master..spt_values v ON v.type = 'P'
AND v.number BETWEEN 1 AND CASE WHEN m.maxMin < 90 THEN 90 ELSE m.maxMin END
LEFT JOIN scoresByMinute s ON m.matchID = s.matchID and v.number = s.minute
),
filledscorelines AS (
SELECT
matchID,
minute,
scoreline = COALESCE(scoreline, '00')
FROM allminutes
WHERE minute = 1
UNION ALL
SELECT
m.matchID,
m.minute,
scoreline = COALESCE(m.scoreline, s.scoreline)
FROM allminutes m
INNER JOIN filledscorelines s ON m.matchID = s.matchID
AND m.minute = s.minute + 1
)
SELECT *
FROM filledscorelines
ORDER BY matchID, minute
答案 1 :(得分:2)
创建一个包含所需结构的新表,然后为每个匹配项运行
declare @counter int
declare @scoreline varchar(10)
declare @matchID int
set @counter = 1
set @matchID = 1
set @scoreline = '00'
while (@counter <= 90)
begin
select @scoreline = ISNULL(scoreline,@scoreline) from scores where minute = @counter
insert into filledScoreLines(matchID, minute, scoreline)
select @matchID as matchID, @counter as min, @scoreline as scoreline
set @counter = @counter + 1
end
要为多个匹配执行此操作,只需遍历您拥有的所有匹配ID - 如下所示:
declare @matchID int
declare getEm cursor local for select distinct matchID from scoresByMinute
open getEm
while (1=1)
begin
fetch next from getEm into @matchID
if (@@fetch_status 0)
begin
DEALLOCATE getEm
break
end
declare @counter int
declare @scoreline varchar(10)
set @counter = 1
set @scoreline = '00'
while (@counter <= 90)
begin
select @scoreline = ISNULL(scoreline,@scoreline) from scores where minute = @counter
insert into filledScoreLines(matchID, minute, scoreline)
select @matchID as matchID, @counter as min, @scoreline as scoreline
set @counter = @counter + 1
end
end