我在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个别名列NextStartDate
,NextDestination
从当前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
WHERE
子句不适用于列别名,我似乎无法使HAVING
工作。
答案 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'