Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello i am working on attendance system using c# and sql server for the first time i am facing a problem mentioned below

i have some records like this


Student_Name | Attendance | Class

      Jones                   P            Grade 1
      Smith                  P            Grade 1
     Raven                  A            Grade 1
     Jash                      L            Grade 1


now i want this retrieve this record


Class    |    NoOfStduent | NoOfPresents | NoOfAbsents | NoOfLeaves

Grade 1                4                 2                        1                       1


Is this possible using case ?
Posted

You can use select Class, Attendance, count(*) as No from <table> group by Class, Attendance</table>

Then use this as the inner query on a pivot to transform the data to how you need.

SQL
select Class, P+A+L as Students, P as Present, A as Absent, L as Leaves
from (select Class, Attendance, count(*) as No 
    from <table> 
    group by Class, Attendance
) src Pivot ( sum(No) for Attendance in ( [P], [A], [L] )) pvt
</table>
 
Share this answer
 
v2
Comments
Andrius Leonavicius 8-Apr-14 17:33pm    
+5
another way...
SQL
SELECT  Class, SUM(Students) NoOfStduent ,SUM(Presents) NoOfPresents ,SUM(Absents) NoOfAbsents ,SUM(Leaves) NoOfLeaves
FROM
(
    SELECT
        Class,
        1 as Students,
        CASE WHEN Attendance = 'P' THEN 1 ELSE 0 END AS Presents,
        CASE WHEN Attendance = 'A' THEN 1 ELSE 0 END AS Absents,
        CASE WHEN Attendance = 'L' THEN 1 ELSE 0 END AS Leaves
    FROM    tableName
) as a
GROUP BY Class

Happy Coding!
:)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900