1

我已经为此苦苦挣扎了很长时间...我正在尝试在 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
4

2 回答 2

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
于 2012-08-27T20:38:12.690 回答
0
SELECT 前提_id,SUM(s.[1st]) AS [1st],SUM(s.[2nd]) AS [2nd]
从 (
    SELECT 前提_id,MAX(date_cleaned) AS [1st],NULL AS [2nd]
    从清洁
    GROUP BY 前提_id
    联盟
    SELECT 前提 ID,NULL AS [1st],MAX(date_cleaned) AS [2nd]
    从清洁
    左连接
    (
        SELECT 前提_id,MAX(date_cleaned) AS [1st],NULL AS [2nd]
        从清洁
        GROUP BY 前提_id
    ) AS t ON 清洁.前提_id = t.前提_id 和清洁.date_cleaned t.date_cleaned
    GROUP BY 前提_id
) 年代

于 2012-08-27T20:20:20.310 回答