SQL:SELECT MAX(Date)涉及几个表

时间:2012-02-23 11:39:24

标签: sql ms-access

我有一个包含四个表的小型MS Access数据库,并且正在使用涉及所有表的MAX(日期)查询。任何帮助将不胜感激。

数据库概述:

TABLE          COLUMNS

Person         Person_ID |....
Games          Game_ID | Name |....
Played_Games   Played_Games_ID | Game_ID | Date |....
Participation  Played_Games_ID | Person_ID |...

列出所有游戏以及我使用的任何人最后一次玩这些游戏的日期:

SELECT DISTINCT Games.Name,
(SELECT MAX(Date) FROM Played_Games WHERE Played_Games.Game_ID = Games.Game_ID) AS Date_Last_Played
FROM Games
ORDER BY Games.Name

这很有效,但我还想列出某一群人的最后一次扮演的日期。任何帮助都将非常感激。

我几天前问过similar question,但后来我的目标是列出所有游戏,每场比赛总共玩了多少次,以及某个组的成员每场比赛玩了多少次人(人1和人2只是一个例子)。 GarethD通过以下代码帮助我完成了那个完美的工作。我试图改变这个代码来解决我的新任务,因为我猜这个逻辑/结构的大部分都可以重复使用,但到目前为止我还没有成功: - (

SELECT  Games.Name,
        IIF(ISNULL(TimesPlayed),0,TimesPlayed) AS Times_Played,
        IIF(ISNULL(TimesPlayedByGroupMembers),0,TimesPlayedByGroupMembers) AS Times_Played_By_Group_Members
FROM    Games
        LEFT JOIN
        (   SELECT  Game_ID,
                    COUNT(*) AS TimesPlayed,
                    SUM(IIF(ISNULL(Participation.Played_Games_ID),0,1)) AS TimesPlayedByGroupMembers
            FROM    Played_Games
                    LEFT JOIN
                    (   SELECT  Played_games_ID
                        FROM    Participation
                        WHERE   Person_ID IN (1, 2)
                        GROUP BY Played_games_ID
                    ) AS Participation
                     ON Participation.Played_Games_ID = Played_Games.Played_Games_ID
            GROUP BY Game_ID
        ) AS Played_Games
            ON Played_Games.Game_ID = Games.Game_ID
ORDER BY Games.Name

任何帮助将不胜感激。谢谢你的时间!

1 个答案:

答案 0 :(得分:1)

我刚刚在最后一个回答中添加了几行,以显示上次播放的日期,以及群组成员上次播放的日期,旁边播放的次数。希望这就是你所追求的。

SELECT  Games.Name,
        IIF(ISNULL(TimesPlayed),0,TimesPlayed) AS Times_Played,
        IIF(ISNULL(TimesPlayedByGroupMembers),0,TimesPlayedByGroupMembers) AS Times_Played_By_Group_Members,
        LastPlayed,
        LastPlayedByGroupMembers
FROM    Games
        LEFT JOIN
        (   SELECT  Game_ID,
                    COUNT(*) AS TimesPlayed,
                    SUM(IIF(ISNULL(Participation.Played_Games_ID),0,1)) AS TimesPlayedByGroupMembers,
                    MAX(Played_Games.[Date]) AS LastPlayed,
                    MAX(IIF(ISNULL(Participation.Played_Games_ID),NULL,Played_Games.[Date])) AS LastPlayedByGroupMembers
            FROM    Played_Games
                    LEFT JOIN
                    (   SELECT  Played_games_ID
                        FROM    Participation
                        WHERE   Person_ID IN (1, 2)
                        GROUP BY Played_games_ID
                    ) AS Participation
                     ON Participation.Played_Games_ID = Played_Games.Played_Games_ID
            GROUP BY Game_ID
        ) AS Played_Games
            ON Played_Games.Game_ID = Games.Game_ID
ORDER BY Games.Name