2015-07-02 57 views
2

我在MS-Access,它運行正常以下查詢:篩選的別名的列

SELECT A1.LRN, A1.StartDate, A1.Destination, 
(
    SELECT TOP 1 A2.StartDate 
    FROM testEnrolment As A2 
    WHERE A2.LRN = A1.LRN AND A2.StartDate > A1.StartDate 
    ORDER BY A2.StartDate 
) As NextStartDate, 
(
    SELECT TOP 1 B2.Destination 
    FROM testEnrolment As B2 
    WHERE B2.LRN = A1.LRN AND B2.StartDate > A1.StartDate 
    ORDER BY B2.StartDate 
) As NextDestination 
FROM testEnrolment As A1 

的2分別名列NextStartDateNextDestination得到他們的數據來自StartDate,併爲下一個記錄的Destination領域當前LRN

因此,如果表testEnrolment有這樣的數據:

LRN StartDate Destination 
-------------------------------- 
L0001 01/08/2014 Unemployed 
L0001 02/08/2014 Education 
L0001 03/08/2014 Unemployed 
L0002 20/09/2014 Education 
L0002 21/09/2014 

查詢將導致本:

LRN StartDate Destination NextStartDate NextDestination 
-------------------------------------------------------------- 
L0001 01/08/2014 Unemployed 02/08/2014  Education 
L0001 02/08/2014 Education 03/08/2014  Unemployed 
L0001 03/08/2014 Unemployed 
L0002 20/09/2014 Education 21/09/2014 
L0002 21/09/2014 

我想接下來要做的是過濾由記錄的列別名NextDestination不等於「教育」。

A WHERE子句將不會在列別名上工作,我似乎也無法使HAVING工作。

回答

1

包裝你的SQL到一個子查詢,以便您可以在別名過濾

SELECT * FROM (
SELECT A1.LRN, A1.StartDate, A1.Destination, 
(
    SELECT TOP 1 A2.StartDate 
    FROM testEnrolment As A2 
    WHERE A2.LRN = A1.LRN AND A2.StartDate > A1.StartDate 
    ORDER BY A2.StartDate 
) As NextStartDate, 
(
    SELECT TOP 1 B2.Destination 
    FROM testEnrolment As B2 
    WHERE B2.LRN = A1.LRN AND B2.StartDate > A1.StartDate 
    ORDER BY B2.StartDate 
) As NextDestination 
FROM testEnrolment As A1 
) AS s 
WHERE NextDestination <> 'Education' 
+0

謝謝 - 很高興有一個簡單的解決方案:) –