我正在尝试返回员工姓名和奖励日期如果他们在用户指定的日期之前没有先前的奖励日期(这些是表单上的字段,StartDateTxt
和{{1如下所示),又名他们的“第一次出现”。
示例(仅为简单起见,AwardTbl):
EndDateTxt
如果我在日期AwardDate EmployeeID PlanID AwardedUnits
3/1/2005 100200 1 3
3/1/2008 100200 1 7
3/1/2005 100300 1 5
3/1/2013 100300 1 8
之间运行查询,则会返回1/1/2005 - 12/31/2005
和3/1/2005
以及100200
。如果我在100300
之间运行查询,则会返回任何内容,同样会返回1/1/2008-12/31/2008
,因为这些员工已经拥有较早的奖励日期。
我尝试了几个不同的东西,这给了我一些奇怪的结果。
1/1/2013 - 12/31/2013
此查询不关心是否有以前的记录,我认为这是我不确定如何缩小查询的地方。
我也尝试过:
SELECT x.AstFirstName ,
x.AstLastName ,
y.AwardDate ,
y.AwardUnits ,
z.PlanDesc
FROM (AssociateTbl AS x
INNER JOIN AwardTbl AS y ON x.EmployeeID = y.EmployeeID)
INNER JOIN PlanTbl AS z ON y.PlanID = z.PlanID
WHERE y.AwardDate BETWEEN [Forms]![PlanFrm]![ReportSelectSbfrm].[Form]![StartDateTxt] And [Forms]![PlanFrm]![ReportSelectSbfrm].[Form]![EndDateTxt] ;
(没有用)Min(AwardDate)
子句中按WHERE
排序的子查询,只返回1条记录TOP 1 AwardDate ASC
(这也不区分是否是第一次出现AwardDate)请注意:这是MS Access。没有DCount("*", "AwardTbl", "AwardDate < [Forms]![PlanFrm]![ReportSelectSbfrm].[Form]![StartDateTxt]") < 1
或ROW_NUMBER()
功能。
答案 0 :(得分:1)
尝试以下
SELECT x.AstFirstName ,
x.AstLastName ,
y.AwardDate ,
y.AwardUnits ,
z.PlanDesc
FROM (AssociateTbl AS x
INNER JOIN AwardTbl AS y
ON x.EmployeeID = y.EmployeeID)
INNER JOIN PlanTbl AS z
ON y.PlanID = z.PlanID
WHERE y.AwardDate BETWEEN '1/1/2005' AND '12/31/2005'
GROUP BY y.EmployeeID,
x.AstFirstName ,
x.AstLastName ,
y.AwardDate ,
y.AwardUnits ,
z.PlanDesc
HAVING COUNT(*) = 1
答案 1 :(得分:1)
我相信你需要一个嵌套的选择。嵌套查询将选择Min(awardDate),外部查询将过滤您想要的时间段。
如果您在同一个查询中同时使用它,它会在Min(awardDate)在指定时间内返回Min(awardDate)之前过滤掉结果。
select y.employeeId, y.awardDate from (
select x.employeeId, min(x.awardDate) as awardDate
from AssociateTbl as x
group by x.employeeId) as y
where y.awardDate >= :startAwardDate and y.awardDate < :endAwardDate;
答案 2 :(得分:1)
如果根据Having
子句中的日期范围将EmployeeID分组并用作过滤器列表,则最小奖励日期将起作用:
SELECT x.AstFirstName ,
x.AstLastName ,
y.AwardDate ,
y.AwardUnits ,
z.PlanDesc
FROM ((AssociateTbl AS x
INNER JOIN AwardTbl AS y ON x.EmployeeID = y.EmployeeID)
INNER JOIN (select a.EmployeeID,min(a.AwardDate) AS MinAwardDate
from AwardTbl AS a
group by a.EmployeeID
having ((min(a.awardDate)>=[Forms]![PlanFrm]![ReportSelectSbfrm].[Form]![StartDateTxt]
and min(a.awardDate)<[Forms]![PlanFrm]![ReportSelectSbfrm].[Form]![EndDateTxt]))
) AS d on d.EmployeeID = x.EmployeeID
and d.MinAwardDate = y.AwardDate)
INNER JOIN PlanTbl AS z ON y.PlanID = z.PlanID