2012-08-27 3 views
1

나는 이걸로 오랫동안 고민했습니다 ... 서비스 테이블에서 가장 최근 및 둘째 가장 최근 서비스 날짜를 끌어 오기 위해 Access에서 SQL 문을 작성하려고합니다. Cleaning이라고합니다.GROUP BY 마지막 및 두 번째 마지막 레코드

샘플 원시 데이터 :

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은 얻을 것이다 :이 제출 내가 그것을 원하는 방식의 형식을 didnt는

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

! 그러나 좀 더 명확히하기 위해 : 나는 lastDate와 SecondLastDate GROUPED BY Premises_No를 줄 보고서를 작성하려고합니다. 다시 한 번 감사드립니다! – user1628496

+0

테이블에 고유 한 ID가 있습니까? 아니면 추가 할 수 있습니까? – Fionnuala

+0

아마도 premise_id 및이 http://stackoverflow.com/questions/32100/what-is-the-simplest-sql-query-to-find-the-second에 의해 정리 그룹에서 선택한 premise_id, max (date_cleaned)를 혼합 한 것입니다. - 가장 큰 가치 –

답변

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 

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 
관련 문제