我通过sql查询,其中列出了先前比赛的所有赛马表现。我只想列出他们最近的9场演出。
一段时间以来,我一直在寻找一个答案,搜索各种站点,但找不到合适的答案。我将不胜感激任何帮助。
SELECT Form1.Horse, Form1.Date, Form1.[Mile Rate], Form1.[Beaten M], Form1.Distance, Form1.[M or S], Form1.[Class], Form1.[1Q], Form1.[2Q], Form1.[3Q], Form1.Bar, Form1.Driver, Form1.Comment, Form1.Trainer, Form1.Adj, Form1.[Race%], Form1.[Bell Pos], Form1.Pegs, Form1.[Adj LH], Form1.[M LastL], Form1.[Track]
FROM Form1
WHERE Horse in ('SOHO PICASSO','LITTLE BITOF FUN','BEEJAYS STAR','MISS STARFIRE','MEDIEVAL MAN','BLUE STONE','SOHO MAJOR PLAYER NZ','HUMBLE FELLA','STARS OF GOLD','MISS SERENA','MISS MARGARETA','NIGHTWATCH STAR','PURE IMAGE','VILLAGE BENNY','CAPTAIN CROISSANT','JESSIE JOAN','THE GLASS CEILING','BROOK PARKS LAST','ANTAGONISTIC NZ');
答案 0 :(得分:1)
使用ROW_NUMBER功能。
SELECT*
FROM(
SELECT Form1.Horse, Form1.Date, Form1.[Mile Rate], Form1.[Beaten M], Form1.Distance, Form1.[M or S], Form1.[Class], Form1.[1Q], Form1.[2Q], Form1.[3Q], Form1.Bar, Form1.Driver, Form1.Comment, Form1.Trainer, Form1.Adj, Form1.[Race%], Form1.[Bell Pos], Form1.Pegs, Form1.[Adj LH], Form1.[M LastL], Form1.[Track]
,ROW_NUMBER() OVER(PARTITION BY Horse ORDER BY Date) rn
FROM Form1
WHERE Horse in ('SOHO PICASSO','LITTLE BITOF FUN','BEEJAYS STAR','MISS STARFIRE','MEDIEVAL MAN','BLUE STONE','SOHO MAJOR PLAYER NZ','HUMBLE FELLA','STARS OF GOLD','MISS SERENA','MISS MARGARETA','NIGHTWATCH STAR','PURE IMAGE','VILLAGE BENNY','CAPTAIN CROISSANT','JESSIE JOAN','THE GLASS CEILING','BROOK PARKS LAST','ANTAGONISTIC NZ')
)T
WHERE rn <= 9
如果您的数据库不支持ROW_NUMBER
,请使用该查询:
SELECT Form1.Horse, Form1.Date, Form1.[Mile Rate], Form1.[Beaten M], Form1.Distance, Form1.[M or S], Form1.[Class], Form1.[1Q], Form1.[2Q], Form1.[3Q], Form1.Bar, Form1.Driver, Form1.Comment, Form1.Trainer, Form1.Adj, Form1.[Race%], Form1.[Bell Pos], Form1.Pegs, Form1.[Adj LH], Form1.[M LastL], Form1.[Track]
FROM (
SELECT t1.Horse, t1.Date, COUNT(*) AS rn
FROM Form1 AS t1
INNER JOIN Form1 AS t2
ON t2.Horse = t1.Horse
AND t2.Date >= t1.Date
GROUP BY t1.Horse, t1.Date
HAVING COUNT(*) <= 9
)t
INNER JOIN Form1
ON Form1.Horse = t.Horse
AND Form1.Date = t.Date
内部查询模拟ROW_NUMBER并使用rn <= 9
过滤到行。
答案 1 :(得分:-1)
您可以使用SELECT TOP
Link to documentation