我遇到了 SQL 查询问题。我有一个包含 145 个站点名称的列表。在每个地点都发现了某些物种。我计算了每个物种在每个地点出现的次数。我想找到在每个地点看到的 5 种最常见的物种。目前我有:
SELECT TOP 5 Count([bird point counts bound query].[Group size]) AS [CountOfGroup size], [bird point counts bound query].site, [bird point counts bound query].Species
FROM [bird point counts bound query]
GROUP BY [bird point counts bound query].site, [bird point counts bound query].Species
ORDER BY Count([bird point counts bound query].[Group size]) DESC;
这仅返回所有站点中最常见的 5 个物种。澄清一下,根据每个站点和 145 个站点的前 5 个结果,结果表应包含 725 条记录。我目前在 Access 工作。
感谢任何帮助,因为 SQL 不是我的强项。
最佳答案
据我所知,您只能使用 Access 中的临时表来完成此操作。
类似的东西?
CREATE TABLE ##SiteSpecies (
id int IDENTITY (1,1),
Site <whatever>,
Species <whatever>,
Observations int
)
INSERT INTO ##SiteSpecies
SELECT [bird point counts bound query].site, [bird point counts bound query].Species, Count([bird point counts bound query].[Group size])
FROM [bird point counts bound query]
GROUP BY [bird point counts bound query].site, [bird point counts bound query].Species
ORDER BY [bird point counts bound query].site, [bird point counts bound query].Species, Count([bird point counts bound query].[Group size])
SELECT
results.*
FROM
##SiteSpecies AS results
INNER JOIN
(
SELECT Site, MIN(id) AS FirstID FROM ##SiteSpecies GROUP BY Site
)
AS SiteMarkers
ON results.Site = SiteMarkers.Site
AND results.id <= SiteMarkers.FirstID + 4
关于SQL TOP 结果按字段分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10574662/