Skip to content
Advertisement

SQLite – How to perform COUNT() with a WHERE condition?

I have a products table with these fields: _id, product_name, priority and shelf_id.

And I have a shelves table with these fields: _id and shelf_name.

Currently, I have this SQL which returns a resultset showing the name of each shelf along with the number of products within each shelf:

What I am trying to achieve is the creation of an additional column in the resultset that will show the number of products in each shelf that have a priority value that is greater than zero. Something along the lines of…

…but valid, of course.

I have searched for sqlite subqueries and found this tutorial, but it doesn’t seem to be what I’m after.

Could someone help me out with a push in the right direction or, even better, modify my SQL query so that it will return valid num_products_in_shelf_with_priority data.

Advertisement

Answer

You can include a case condition and then sum it. Also, included is the shelf_name in the group by clause.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement