Home Forums SQL Server 2008 T-SQL (SS2K8) In --> Group By with Multiple columns...> how it will responds RE: In --> Group By with Multiple columns...> how it will responds

  • Below is a basic example for Group By

    CREATE TABLE #Studentcourseschedule(

    Department int,

    Courseid int,

    studentid int)

    go

    insert into #Studentcourseschedule(Department, Courseid,studentid)

    values(1,1,1)

    ,(1,2,1)

    ,(1,3,1)

    ,(1,1,5)

    ,(1,3,6)

    ,(1,1,7)

    ,(2,2,1)

    ,(2,1,2)

    ,(2,3,2)

    go

    select department, COUNT(studentid) Studentcount

    from #Studentcourseschedule

    group by department

    order by Department

    go

    select department, courseid, COUNT(studentid) Studentcount

    from #Studentcourseschedule

    group by department,courseid

    order by Department, Courseid

    1st Query Result:

    department Studentcount

    1 6

    2 3

    2nd Query Result

    departmentcourseidStudentcount

    1 1 3

    1 2 1

    1 3 2

    2 1 1

    2 2 1

    2 3 1

    In the first query the grouping is done only on Department, so it checks the no of students in each of the Department available in the table which is 1 and 2 in example

    When we add another group by column on courseid, now it looks for the each course available under each department and displays count of the student in that department and course.