在sql server中构建sql查询的困惑

时间:2011-06-15 08:53:55

标签: sql sql-server

我的表格与下面的内容完全相同

School              Course              Date             Status

SCH1            SCH1CRS1        2011-01-15           S

                SCH1CRS1        2011-01-17           C

SCH1            SCH1CRS2        2011-01-15           S

SCH2            SCH2CRS1        2011-01-15           S

                SCH2CRS1        2011-01-21           C

SCH2             SCH2CRS2        2011-01-22          S

               SCH2CRS2          2011-01-25          C

状态S =已开始且C =已完成,日期为开始日期和完成日期。当课程开始时,用户输入schoolID,courseID,日期和状态,但是当课程完成后,用户输入courseID,日期和状态。用户不输入SchoolID。从表中我们可以理解SCH1CRS1和SCH1CRS2属于SCH1。我需要知道的是,在某个特定的学校,在特定的日期,有多少课程已经开始但尚未完成。

您可以在SCH1中看到,2011-01-15已经开始了两个课程,但只有一个课程已经完成。课程何时完成并不重要。我需要知道的是否已经完成。在SCH2中,两门课程在不同的日期开始,但都已完成。

结果表应该是这样的

Input Date: 2011-01-15

School             Not completed  

SCH1                       1

SCH2                       0

Input Date: 2011-01-22

School           Not Completed

SCH2                      0 

我认为这是一个混乱的表,并没有遵循数据库设计规则。但这就是我所拥有的。没有选择。

由于

3 个答案:

答案 0 :(得分:0)

您必须找到与已开始课程相关的已完成课程,如果没有完成课程,请计1。

SELECT startedCourse.School AS School, 
       SUM(CASE WHEN completedCourse IS NULL THEN 1 ELSE 0 END) AS NotCompleted
FROM MyTable startedCourse
    LEFT OUTER JOIN MyTable completedCourse
        ON startedCourse.Status = 'S'
        AND completedCourse.Status = 'C'
        AND startedCourse.Course = completedCourse.Course
WHERE startedCourse.Date = ?
GROUP BY startedCourse.School

答案 1 :(得分:0)

从头顶开始:

select c_started.courseID, c_started.courseDate as StartDate, c_completed.courseDate as CompletedDate, 
case 
 when c_completed.courseDate IS NULL then 'incomplete'
 Else 'completed'
end as courseStatus
from tbCourses as c_started
left join tbCourses as c_completed on c_started.courseID = c_completed.courseID 
and c_started.courseDate < c_completed.courseDate
where c_started.Status = 'S'

会给你以下内容:

courseID - StartDate - CompletedDate - courseStatus

course1 - 2010-01-12 - 2010-02-25 - 已完成

course2 - 2011-01-21 - NULL - 不完整

course3 - 2010-10-15 - NULL - 不完整

答案 2 :(得分:0)

这个怎么样:

declare @InputDate datetime = '20110115';

with cCourseList as (

select  t1.School, t1.Course, DateStarted = t1.Date,
        t2.DateCompleted
from    tbl t1
outer apply 
        (select  top(1) DateCompleted = t2.Date
        from    tbl t2
        where   t2.Course = t1.Course
            and t2.Status = 'C'
        order by t2.Date) t2
where   t1.Status = 'S'

)

select  cl.School, 
        [Not Completed] = sum(case when cl.DateCompleted is null then 1 else 0 end)
from    cCourseList cl
where   cl.DateStarted <= @InputDate
group by cl.School;