Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Having troubles with a conditional count in SQL

I’m working on an SQL project (involving a library database) and I’m having a hard time figuring out how to make a conditional count.

So, I have 4 tables: Imprumuturi, Cititori, Autori, Carti. I need to list the ‘Cititori’ that have more than one borrowed ‘Carti’ at the current time.

I tried to use

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT cititori.nume_cititor,COUNT(imprumuturi.pk_cititor) 
AS numar_imprumuturi FROM cititori, imprumuturi 
WHERE imprumuturi.data_return IS NULL GROUP BY cititori.nume_cititor
HAVING COUNT(imprumuturi.pk_cititor)>1 
ORDER BY cititori.nume_cititor;

And while it lists all the ‘Cititori", it doesn’t count the number of active borrowed ‘Carti’ as it should.

Can I get a hint or some help on how to make it work?

These are the fields of my database

>Solution :

seems you missed the relation between the tables

SELECT cititori.nume_cititor,COUNT(imprumuturi.pk_cititor) 
AS numar_imprumuturi 
FROM cititori
INNER JOIN imprumuturi ON imprumuturi.pk_cititori = cititori.pk_cititori
WHERE imprumuturi.data_return IS NULL 
GROUP BY cititori.nume_cititor
HAVING COUNT(imprumuturi.pk_cititor)>1 
ORDER BY cititori.nume_cititor;

As suggestion, You sould not use the old implicit join sintax based on comma separated table’s name and where condition but use explicit join sintax

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading