最后一个和第二个最后一个记录的GROUP BY

时间:2012-08-27 19:33:16

标签: ms-access group-by subquery

我很长时间都在努力... 我试图在Access中编写一个SQL语句,从名为Cleaning的服务表中提取最新和最近的第二个服务日期。

示例原始数据:

Premises_No Date_Cleaned
1           12-Jun
1           15-Jul
1           14-Aug
2           15-Jan
2           18-Feb
2           17-Apr
2           14-May
2           06-Jun
2           11-Jul
2           16-Aug
6           10-Dec
6           12-Jan
6           20-Feb
6           13-Mar
6           15-Apr
6           15-May
6           11-Jun
6           13-Jul
6           10-Aug

因此执行的SQL将产生:

Premises_No MostRecent  2ndMostRecent
1           14-Aug          15-Jun
2           16-Aug          11-Jul
6           10-Aug          13-Jul

2 个答案:

答案 0 :(得分:0)


SELECT premise_id, SUM(s.[1st]) AS [1st], SUM(s.[2nd]) AS [2nd]
FROM (
    SELECT premise_id, MAX(date_cleaned) AS [1st], NULL AS [2nd] 
    FROM cleaning 
    GROUP BY premise_id
    UNION
    SELECT premise_id, NULL AS [1st], MAX(date_cleaned) AS [2nd] 
    FROM cleaning 
    LEFT JOIN
    (
        SELECT premise_id, MAX(date_cleaned) AS [1st], NULL AS [2nd] 
        FROM cleaning 
        GROUP BY premise_id
    ) AS t ON cleaning.premise_id = t.premise_id and cleaning.date_cleaned  t.date_cleaned
    GROUP BY premise_id
) s 

答案 1 :(得分:0)

SELECT last.Premises_No, last.LastCleaned, secondlast.SecondLastCleaned
FROM
(
SELECT c1.Premises_No as Premises_No, Max(c1.Date_Cleaned) AS LastCleaned
FROM Cleaning c1 group by c1.Premises_No
)
as last
LEFT JOIN
(
SELECT c2.Premises_No as Premises_No, Max(c2.Date_Cleaned) AS SecondLastCleaned
FROM Cleaning c2 where c2.Date_Cleaned < (Select Max(c3.Date_Cleaned) FROM Cleaning c3 WHERE c3.Premises_No= c2.Premises_No)
GROUP BY c2.Premises_No
)
as
secondlast
ON last.Premises_No=secondlast.Premises_No