简体   繁体   中英

Using SQL queries in JDBC to group data

I just want to fetch the data from the database through jdbc in NetBeans. I have a table Hostel where the attributes are cid, usid, probs, address, status and the I want to fetch the records and their corresponding number group by cid. I am using the count() function to calculate the number of records for a particular cid.

The query which I am using is

rs = stat.executeQuery("select cid, count(cid), address,usid from hostel" 
      + " where status <> 'processed' group by cid having count(cid)<=5"); 

The error which I am getting is

You tried to execute a query that does not include the specified expression 'address' as part of an aggregate function

Well, your error message is pretty clear, you are trying to output address which is not part of the group by clause. Some databases such as MySQL let you get around with that (they just pick one out of the values), others don't...

Either include all fields in the group by clause (kind of a anti-pattern):

group by cid, address, usid  

Or go with a subquery:

select distinct(h.cid), x.cid_count, h.address, h.usid 
from hostel h,
(
  select hh.cid, count(hh.cid) cid_count
  from hostel hh 
  where hh.status <> 'processed' 
  group by hh.cid 
  having count(hh.cid)<=5
) x
where h.cid = x.cid

Of course that there are many other solutions, small proprietary SOL implementation details specific to each DB (eg, this subquery may not work in your DB because of aliases), etc... In general you can tune your query to achieve better performance (Oracle, for example, supports analytic functions ). But that's a separate question on its own.

If your RDBMS is not MySQL, your fields in SELECT list should be either aggregates or be included in GROUP BY list as well.

This has nothing to do with JDBC in particular but the rule for most SQL implementations.

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