SQL Access GROUP BY和ID

时间:2014-12-01 10:16:17

标签: sql ms-access

我发现了一些例子,但是我很难将这个应用到我的案例中,因为我很快就需要查询,我会找你SQL主人:)

我需要以下SELECT返回Sessions.id(每行对应Max(Sessions.DateFin))

SELECT Sessions.idFormation,
       Inscriptions.idPersonnel, 
       Max(Sessions.DateFin) AS Dernier 
FROM Sessions 
INNER JOIN Inscriptions ON Sessions.id = Inscriptions.idSession 
GROUP BY Sessions.idFormation, Inscriptions.idPersonnel

我相信我需要使用类似的东西(这个与我的上述查询无关,只是来自某个互联网论坛的一个例子)

SELECT * FROM Table1 t1
JOIN 
(
   SELECT category, MAX(date) AS MAXDATE
   FROM Table1
   GROUP BY category
) t2
ON T1.category = t2.category
AND t1.date = t2.MAXDATE

但是因为在我的情况下t1已经是一个查询我不知道如何实现这个解决方案。

3 个答案:

答案 0 :(得分:1)

尝试这样的事情。将其作为Subselect并为alias name提供Subselect,然后加入现有的子选择

SELECT * FROM (--your query--) t1
JOIN 
(
   SELECT category, MAX(date) AS MAXDATE
   FROM Table1
   GROUP BY category
) t2
ON T1.category = t2.category
AND t1.date = t2.MAXDATE

答案 1 :(得分:1)

我想你想要这样的东西:

SELECT s.id, s.idFormation, i.idPersonnel, si.maxdate AS Dernier 
FROM (Sessions as s INNER JOIN
      Inscriptions as i
      ON s.id = i.idSession) INNER JOIN
     (SELECT category, MAX(s.date) as maxdate
      FROM Sessions as s INNER JOIN
           Inscriptions as i
            ON s.id = i.idSession
      GROUP BY s.idFormation, i.idPersonnel
     ) as si
     ON si.category = ??.category AND
        si.maxdate = s.date;

我不知道该类别来自哪个表格;填写而不是??

答案 2 :(得分:0)

这是有效的查询。我确信它可以简化但是如何。

SELECT T1.idFormation AS idFormation, T1.idPersonnel AS idPersonnel, T2.Dernier,     T1.Validé AS Validé 
FROM (SELECT Sessions.idFormation, Inscriptions.idPersonnel, Sessions.DateFin,     Sessions.Validé 
    FROM Sessions 
    INNER JOIN Inscriptions ON Sessions.id = Inscriptions.idSession) T1
INNER JOIN 
( SELECT Sessions.idFormation, Inscriptions.idPersonnel, Max(Sessions.DateFin) AS     Dernier FROM Sessions INNER JOIN Inscriptions ON Sessions.id = Inscriptions.idSession GROUP BY     Sessions.idFormation, Inscriptions.idPersonnel
) T2 
ON T1.idFormation = T2.idFormation 
AND T1.idPersonnel = T2.idPersonnel 
AND T1.DateFin = T2.Dernier