我正在尝试在Microsoft Access中编写一个前n值查询,其中n可能会按组更改。例如,一组可能是前3条记录,另一组可能是前2条记录,另一组可能是前4条记录。我有一个表格,其中包含“TopN”字段,其中我存储了为该组显示的值的数量。
前3个查询的示例有效,我试图用Top N替换Top 3,其中N是DLookup或使用TopN字段中的值的东西:
SELECT Payout.GDate, Payout.[Game Type], Payout.Denom, Payout.Segment, Payout.Manufacturer_Description, Payout.Stand, Payout.Payout
FROM Payout, PayoutShowSegment
WHERE (((Payout.Payout) IN (SELECT TOP 3 [Payout]
FROM [Payout]
WHERE [Payout].[Segment]=[PayoutShowSegment].[Segment])))
ORDER BY Payout.[Game Type], Payout.Denom, Payout.Payout DESC;
答案 0 :(得分:0)
几个月前我遇到过类似的问题。
使用您的查询,这样的事情应该有效:
SELECT T1.GDate,
T1.[Game Type],
T1.Denom,
T1.Segment,
T1.Manufacturer_Description,
T1.Stand,
T1.Payout
FROM Payout T1 INNER JOIN Payout T2 ON
T1.[Game Type] = T2.[Game Type] AND
T1.Denom = T2.Denom AND
T1.Segment = T2.Segment AND
T1.Manufacturer_Description = T2.Manufacturer_Description AND
T1.Stand = T2.Stand AND
T1.Payout = T2.Payout AND
T1.GDate >= T2.GDate
GROUP BY T1.GDate,
T1.[Game Type],
T1.Denom,
T1.Segment,
T1.Manufacturer_Description,
T1.Stand,
T1.Payout
HAVING COUNT(*) <= (
SELECT TopN
FROM MyOtherTable
WHERE MyOtherTable.IDField = T1.IDField
)
ORDER BY T1.GDate
注意 - 联接可能会缩减为Payout表中的PK。
有关详情,请查看此网站:http://www.sql-ex.com/help/select16.php