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:
SELECT
shelves._id AS _id,
shelves.shelf_name AS shelf_name,
COUNT(products._id) AS total_num_products_in_shelf
FROM
shelves
INNER JOIN
products ON shelves._id = products.shelf_id
GROUP BY
shelves._id
HAVING
COUNT(products._id) > 0
ORDER BY
shelf_name ASC
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...
SELECT
shelves._id AS _id,
shelves.shelf_name AS shelf_name,
COUNT(products._id) AS total_num_products_in_shelf,
COUNT(products._id WHERE products.priority > 0) AS num_products_in_shelf_with_priority
...
...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.
SQL SELECT COUNT() can be clubbed with SQL WHERE clause. Using the WHERE clause, we have access to restrict the data to be fed to the COUNT() function and SELECT statement through a condition.
If the <condition> is true, then the count will be calculated based on <expression> passed. Else, NULL is passed in the count() function. In case NULL is passed to count(), it will not get the count of the results, instead it will get the count of the null values in the column your_column_name.
Introduction to SQLite COUNT() functionThe function COUNT() is an aggregate function that returns the number of items in a group. For example, you can use the COUNT() function to get the number of tracks from the tracks table, the number of artists from the artists table, and so on.
SELECT COUNT(*) FROM table_name; The COUNT(*) function will return the total number of items in that group including NULL values. The FROM clause in SQL specifies which table we want to list. You can also use the ALL keyword in the COUNT function.
SELECT
shelves._id AS _id,
shelves.shelf_name AS shelf_name,
COUNT(products._id) AS total_num_products_in_shelf,
sum(case when products.priority > 0 Then 1 else 0 end)
as num_products_in_shelf_with_priority
FROM shelves INNER JOIN products
ON shelves._id = products.shelf_id
GROUP BY shelves._id, shelves.shelf_name
HAVING COUNT(products._id) > 0
ORDER BY shelf_name ASC
You can include a case
condition and then sum
it. Also, included is the shelf_name
in the group by
clause.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With