过滤别名列

时间:2015-07-02 16:22:48

标签: sql ms-access jet

我在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的下一条记录的DestinationLRN字段中获取数据。

因此,如果表格 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

WHERE子句不适用于列别名,我似乎无法使HAVING工作。

1 个答案:

答案 0 :(得分: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'