简体   繁体   中英

Stock system - SQL not showing out of stock items

I have a stock_item table, which houses all stock that has come and gone through my stock system.

Each stock item can be in one of many states, like: 0 ( not_yet_allocated ), 1 ( allocated ), 3 ( returned )... etc.

I am trying to create a notification system that will let me know when I am running low on stock for a specific stock type.

Here is the SQL I have thus far,

SELECT name, status, count(id) AS count
FROM stock_item 
WHERE status IN (0,3) /* Items that are not yet allocated (0), or items that have been returned (3) */
GROUP BY name, status
ORDER BY count ASC;

The above SQL works fine, the only problem is that it does not display a stock type if the WHERE clause is not met, in other words, even though there are no items "in stock" for a certain type, I still need that type to be returned with a count of 0.

You need conditional aggregation to see all the items:

SELECT name, status, sum(case when status IN (0,3) then 1 else 0 end) AS count
FROM stock_item 
GROUP BY si.name, si.status
ORDER BY count ASC;

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