简体   繁体   中英

How to count values in different column of table in sql using java

This is database table named attendance _table and i want to count total no. of absent in all subjects ie total no. absent in MATHS+CA+CN+SP+OOPS. Please help!!!

you can use case to find above sum. Take an idea from this query.

select sum(case when maths = 'ABSENT' then 1 else 0 end) + 
       sum(case when ca = 'ABSENT' then 1 else 0 end) + 
       sum(case when cn = 'ABSENT' then 1 else 0 end) 
from attendance_table;

Note that this answer is not a direct answer to the question...

You have a problem with your data modelling. You don't respect normal form, which make simple operations harder to execute. You should split your table and store Students, Courses and Attendance in separate tables. :

+-----------+------+
| StudentID | Name |
+-----------+------+
| 1         | Max  |
| 2         | Luke |
+-----------+------+

+-----------+-------+
| CourseId  | Title |
+-----------+-------+
| 1         | Math  |
| 2         | CA    |
+-----------+-------+

+--------------+-----------+---------+------------+
| attendenceId | StudentId | CourseId| Attendance |
+--------------+-----------+---------+------------+
| 1            | 1         | 1       | present    |
| 2            | 1         | 2       | absent     |
| 3            | 2         | 1       | present    |
| 4            | 2         | 2       | present    |
+--------------+-----------+---------+------------+

The query now is much simpler and does not need to be changed if you add new courses:

select count(*) from attendance where Attendance = 'absent'

If you want the number of absence for a specific user, it again quite easy. Or the number of absence for a specific course, again, easy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM