简体   繁体   中英

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

I have a situation where i have to count number of strings of same type in one column of a table, for eg. a column would be having values such as A=absent P=present

A A A P P P P P P P A

So i need to count all the strings of same type, like P ie Present that means query should give count result 7. What can be idol query for this?

I think this is the simplest Query that I can think of in terms of SQL Select count(*) from table where attendence='P'

Update: Ensure to use parameterized format of prepared statement in your Java code to prevent SQL Injection.

SELECT attendance, COUNT(*)
FROM Roster
GROUP BY attendance;

Will give you the count of each value in the column. So, for a table having 4 A values and 7 P values, the query will return

attendance | COUNT(*)
___________|_________
           |
A          | 4
P          | 7

Aside: Since your table has repetitive values in its attendance column, you should consider pulling all possible values for attendance out into their own "enumeration" of sorts. SQL doesn't offer enumerations, but there are a few ways to achieve a similar effect.

One method is to create a look up table that contains an ID column (can be an auto-increment), and the values that you want for attendance. Then, in your Roster table, use a foreign key to reference the ID of the correct value.

To save yourself time in the future, you can create a View which uses the attendance values rather than the IDs.

You can read up on Database Normalization if you're interested in improving your database's design.

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