我正在学习SQL并为学校系统工作

时间:2011-02-09 16:48:28

标签: sql sql-server tsql

我的任务是每个EmploymentAssignment行只获得一行,即使工作人员在Employment表中有多行。我是(包括来自现有的员工,会员,就业,学校和部门的员工成员的视图。包括一个新的字段,别名为“districtStart”,报告该人最早的Employment.startDate。)这是我的考试中的问题我无法弄清楚如何让它只拉一个任务。这就是我所拥有的,她说这是正确的,但......它正在拉动一个以上的任务。任何帮助都会让我不再把头撞到墙上。

SELECT
     p.personID,
     p.stateID,
     p.staffNumber,
     p.staffStateID,
     i.identityID,
     i.effectiveDate,
     i.lastName,
     i.firstName,
     i.middleName,
     i.suffix,
     i.alias,
     i.gender,
     i.birthdate,
     i.ssn,
     i.raceEthnicity,
     ea.assignmentID,
     ea.startDate,
     MIN(e.startdate) AS DistrictStart,
     ea.endDate,
     ea.title,
     ea.type,
     ea.teache,
     ea.specialEd,
     ea.behavior,
     ea.health,
     ea.advisor,
     ea.supervisor,
     ea.foodservice,
     ea.departmentID,
     s.schoolID,
     s.name   schoolName,
     s.number schoolNumber,
     d.name   departmentName,
     ea.excludeReferral,
     ea.counselor
FROM     dbo.Person p WITH (NOLOCK)
     INNER JOIN dbo.[Identity] i WITH (NOLOCK)
     ON       p.currentIdentityID = i.identityID
     INNER JOIN dbo.Employment e
     ON       e.personID = p.personID
     INNER JOIN dbo.EmploymentAssignment ea WITH (NOLOCK)
     ON       p.personID = ea.personID
     INNER JOIN dbo.School s WITH (NOLOCK)
     ON       s.schoolID = ea.schoolID
     LEFT OUTER JOIN dbo.Department d WITH (NOLOCK)
     ON       d.departmentID = ea.departmentID
GROUP BY e.startdate,
     p.personID,
     p.stateID,
     p.staffNumber,
     p.staffStateID,
     i.identityID,
     i.effectiveDate,
     i.lastName,
     i.firstName,
     i.middleName,
     i.suffix,
     i.alias,
     i.gender,
     i.birthdate,
     i.ssn,
     i.raceEthnicity,
     ea.assignmentID,
     ea.startDate,
     ea.endDate,
     ea.title,
     ea.type,
     ea.teacher,
     ea.specialEd,
     ea.behavior,
     ea.health,
     ea.advisor,
     ea.supervisor,
     ea.foodservice,
     ea.departmentID,
     s.schoolID,
     s.name,
     s.number,
     d.name,
     ea.excludeReferral,
     ea.counselor

1 个答案:

答案 0 :(得分:1)

你需要从你的小组中逐句取出e.startdate。在您的查询中,您正在使用MIN(e.startdate),但如果您也按照它进行分组,则不会执行任何操作。这是一个简单的例子,向您展示我的意思:

select '20110101' as StartDate
into #DatesExample
union select '20110102' as StartDate
union select '20110103' as StartDate

select min(StartDate)
from #DatesExample
group by StartDate

select min(StartDate)
from #DatesExample