简体   繁体   English

如何使用Java在sql的表的一列中计算不同的值

[英]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 =不存在P =存在

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? 因此,我需要对所有相同类型的字符串进行计数,例如P即存在,这意味着查询应给出计数结果7。对此,偶像查询又是什么呢?

I think this is the simplest Query that I can think of in terms of SQL Select count(*) from table where attendence='P' 我认为这是我可以想到的最简单的查询,它是Select count(*) from table where attendence='P'的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. 更新:确保在Java代码中使用预处理语句的参数化格式,以防止SQL注入。

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 因此,对于具有4 A值和7 P值的表,查询将返回

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. SQL不提供枚举,但是有几种方法可以达到类似的效果。

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. 一种方法是创建一个查找表,其中包含一个ID列(可以是一个自动增量),以及您要用于出勤的值。 Then, in your Roster table, use a foreign key to reference the ID of the correct value. 然后,在您的名册表中,使用外键引用正确值的ID。

To save yourself time in the future, you can create a View which uses the attendance values rather than the IDs. 为了节省以后的时间,您可以创建一个使用出勤值而不是ID的视图。

You can read up on Database Normalization if you're interested in improving your database's design. 如果您对改进数据库的设计感兴趣,可以阅读数据库规范化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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