复杂的MS Access Greatest-N-Per-Group问题

时间:2009-11-26 12:24:24

标签: sql ms-access greatest-n-per-group

我希望将以下查询合并为一个,其中

  • scouting.jumpGate是整数,
  • scouting.astroLoc是一个字符串,
  • scouting.ownerguild是一个字符串
  • scouting.galaxy是一个整数

交叉链接到另一个表(并且是我的GROUP):

    Select TOP 3 
        scouting.jumpGate, 
        scouting.astroLoc, 
        scouting.ownerGuild, 
        scouting.Galaxy 
FROM    scouting 
WHERE   scouting.Galaxy = 1 
AND     scouting.ownerGuild = 'TEST' 
ORDER BY    scouting.jumpGate DESC, 
            scouting.astroloc DESC;

    SELECT TOP 3 
        scouting.jumpGate, 
        scouting.astroLoc, 
        scouting.ownerGuild, 
        scouting.Galaxy 
FROM    scouting 
WHERE   scouting.Galaxy = 2 
AND     scouting.ownerGuild = 'TEST' 
ORDER BY    scouting.jumpGate DESC, 
            scouting.astroloc DESC;

    SELECT TOP 3 
        scouting.jumpGate, 
        scouting.astroLoc, 
        scouting.ownerGuild, 
        scouting.Galaxy 
FROM    scouting 
WHERE   scouting.Galaxy = 3 
AND     scouting.ownerGuild = 'TEST' 
ORDER BY    scouting.jumpGate DESC, 
            scouting.astroloc DESC;

一直持续到

    SELECT TOP 3 
        scouting.jumpGate, 
        scouting.astroLoc, 
        scouting.ownerGuild, 
        scouting.Galaxy 
FROM    scouting 
WHERE   scouting.Galaxy = 79 
AND     scouting.ownerGuild = 'TEST' 
ORDER BY    scouting.jumpGate DESC, 
            scouting.astroloc DESC;

我在微软网站上阅读此最大N每组问题后生成的代码如下:

Select  scouting.astroLoc, 
        scouting.galaxy, 
        scouting.jumpGate, 
        scouting.ownerGuild 
From    galaxy Inner Join 
        scouting On galaxy.[galaxy_ID] = scouting.galaxy 
Where   scouting.ownerGuild = 'SWARM' 
AND     (scouting.jumpGate) In (Select Top 3 scouting.jumpGate From scouting Where scouting.galaxy = galaxy.[galaxy_ID] Order By scouting.jumpGate Desc) 
Order By    scouting.astroLoc Desc, 
            scouting.jumpGate Desc

基本上,这与我想要的非常接近。一切似乎都有效。然而,即使在考虑数据之后,一些GROUPS也没有在输出中表示,每个组都有一个满足查询约束的记录。顺便说一句,如果我取出scouting.ownerGuild ='SWARM'约束,它可以完美地工作(但我需要这个约束)。

1 个答案:

答案 0 :(得分:0)

怎么样:

Select  scouting.astroLoc, 
        scouting.galaxy, 
        scouting.jumpGate, 
        scouting.ownerGuild 
From    galaxy Inner Join 
        scouting On galaxy.[galaxy_ID] = scouting.galaxy 
WHERE   (scouting.ID) In (
             Select Top 3 scouting.ID
             From scouting 
             Where scouting.galaxy = galaxy.[galaxy_ID] 
             And scouting.ownerGuild = 'SWARM' 
             Order By scouting.jumpGate Desc) 
Order By    scouting.astroLoc Desc, 
                scouting.jumpGate Desc

否则前3名可能包含一些

  where scouting.ownerGuild <> 'SWARM'