返回结果在MS Access中按水平分组

时间:2016-10-06 11:06:26

标签: ms-access

这是MS Access问题

我有一个看起来像这样的表:

Stuff        Type
-----        -----
Car          Chevy
Car          Honda
Pet          Cat
Electronic   TV
Electronic   Phone
Electronic   Computer

希望它看起来像这样:

Stuff    Type1   Type2   Type3
------     ----    -----   -----
Car       Chevy   Honda
Pet         Cat
Electronic  TV     Phone   Computer

只需要找到组中的前3个返回项

1 个答案:

答案 0 :(得分:0)

这假设您在表格中有一个id字段,因为您说您只想返回前三个项目:

SELECT MyThings.Stuff, 
   Max(IIf([SRT]=1,[Type],Null)) AS Type1, 
   Max(IIf([SRT]=2,[Type],Null)) AS Type2, 
   Max(IIf([SRT]=3,[Type],Null)) AS Type3
FROM (SELECT MyTable.id, MyTable.Stuff, MyTable.Type, 
     (SELECT COUNT(id) FROM MyTable T WHERE T.Stuff = MyTable.Stuff AND
        T.id <= MyTable.id) AS SRT
      FROM MyTable) AS MyThings
WHERE (((MyThings.SRT)<=3))
GROUP BY MyThings.Stuff
ORDER BY Min(MyThings.id)

只要预定义类型数量,此方法就适合您。