【问题标题】:Filtering an aliased column过滤别名列
【发布时间】:2015-07-02 16:22:47
【问题描述】:

我在 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

NextStartDateNextDestination 这两个别名列从当前LRN 的下一条记录的StartDateDestination 字段中获取数据。

所以如果表 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 工作。

【问题讨论】:

    标签: sql ms-access jet


    【解决方案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'
    

    【讨论】:

    • 谢谢 - 很高兴有一个简单的解决方案 :)
    猜你喜欢
    • 2014-06-28
    • 2014-09-18
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    相关资源
    最近更新 更多