根据SQL Server中的条件从Count计数

时间:2015-03-15 08:59:58

标签: sql-server

我的数据库中有4个表。

  1. StudentsIdno, Name, CourseId
  2. 示例数据:

    Idno    Name    CourseId
    ------------------------
    -101123456  Vijay   101
    -101123457  John    102
    -101123458  Sam 101
    -101123459  Arvind  102
    -101123460  Smith   101
    
    1. CoursesCourseId, CourseNo, CourseName, StreamId
    2. 示例数据:

      CourseId    CourseNo     CourseName StreamId
      ------------------------------------------
      -101    53245   C   1
      -102    53245   C++ 2
      
      1. StreamsStreamId, StreamName
      2. 示例数据:

        StreamId    StreamName  
        ---------------------------
        -1          Engineering
        -2          Medical
        
        1. BookingBId, Idno, BStatus
        2. 示例数据:

          Bid     Idno        BStatus
          --------------------------------
          -1110   101123456   Confirmed
          -1111   101123456   Confirmed
          -1112   101123457   Confirmed
          -1113   101123458   Confirmed
          -1114   101123459   Confirmed
          -1115   101123460   Confirmed
          -1116   101123456   Confirmed
          -1117   101123457   Confirmed
          -1118   101123458   Confirmed
          -1119   101123459   Confirmed
          -1119   101123460   Cancelled
          

          我在生成以下输出时遇到问题

          SNo Stream        BookedOnce BookedTwice NonBooked
          1    Engineering     2           3         0
          2    Medical         3           1          1
          

          由于

1 个答案:

答案 0 :(得分:1)

我认为这需要两个步骤。首先,计算每个学生对流的预订数量。然后按流,计算有一次,两次或零预订的学生人数。

以下是一个示例,内部查询的第一步是:

select  StreamId
,       StreamName
,       sum(case when Bookings = 1 then 1 else 0 end) as BookedOnce
,       sum(case when Bookings = 2 then 1 else 0 end) as BookedTwice
,       sum(case when Bookings = 0 then 1 else 0 end) as NoneBooked
from    (
        select  str.StreamId
        ,       str.StreamName
        ,       s.Idno
        ,       count(b.BId) as Bookings
        from    Students s
        left join
                Booking b
        on      b.Idno = s.Idno
        left join
                Courses c
        on      c.CourseId = s.CourseId
        left join
                Streams str
        on      str.StreamId = c.StreamId
        group by        
                str.StreamId
        ,       str.StreamName
        ,       s.Idno
        ) BookingsPerStudentPerStream
group by        
        StreamId
,       StreamName