简体   繁体   中英

MYSQL - COUNT() NULL Values

This has been racking my head. I've scoured the internet (including this place) and can't find a solution. So as a last resort I was hoping the good people of this forum might be able to help me out.

I have two tables:

TableA
Order_detailsID 
OrderID
TitleID
Return_date

TableB
TitleID
Title_name
Quantity_in_stock

And would like to run a query that shows the remaining 'Quantity_in_stock'.

If the 'Return_date' is set to NULL then it means the item is currently out -- so I have been trying to use the count() function for the NULL values and subtract it from the 'Quantity_in_stock'.

This is the script I have so far:

DELIMITER //
 CREATE PROCEDURE InStock()
BEGIN

Select TableB.TitleID,
TableB.Title_name,
TableB.Quantity_in_stock AS 'Total_Stock',
COUNT(TableA.return_date IS NULL) AS 'Rented_Out',
TableB.Quantity_in_stock - COUNT(TableA.return_date IS NULL) AS 'Remaining Stock'
From TableB
LEFT JOIN TableA
ON TableA.TitleID = TableB.TitleID
GROUP BY TableB.TitleID;

END//

This works if there is one of more of the TitleIDs at NULL, however if there are no values at NULL, then the Count() is still returning a value of 1 when it should be 0.

What am I doing wrong?

Instead of:

COUNT(TableA.return_date IS NULL)

use this:

SUM(CASE 
        WHEN TableA.TitleID IS NULL THEN 0
        WHEN TableA.return_date IS NOT NULL THEN 0
        ELSE 1
      END)

The problem with the TableA.return_date IS NULL predicate is that it's true in two completely different situations:

  1. When there is no matching record in TableA
  2. When there is a matching record but TableA.return_date value of this exact record is NULL .

Using the CASE expression you can differentiate between these two cases.

我想在这里提一个简单的概念,只要在特定列为null时继续计算行数。

select count(*) from table_name where column_name is null

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