Count all values from Column A but only certain values from Column B

KulaMa :

(1) Table (SQL Fiddle):

CREATE TABLE Sales (
    Product Text,
    Sales_Monetary VARCHAR(255),
    Returns_Monetary VARCHAR(255)
);

INSERT INTO Sales
(Product, Sales_Monetary, Returns_Monetary)
VALUES 
("Product A", "500", "300"),
("Product A", "200", "130"),
("Product A", "600", "0"),
("Product A", "900", "540"),
("Product B", "150", "70"),
("Product B", "480", "0"),
("Product B", "220", "0"),
("Product B", "300", "0"),
("Product B", "890", "670"),
("Product C", "360", "0"),
("Product C", "740", "530");

(2) Desired Result:

            Sold_Items   Returned_Items    Return_Rate_Items
Product A      4            3                  0.75
Product B      5            2                  0.4
Product C      2            1                  0.5

I want to get the Return Rate based on items from the example table above.
Therefore, I want to use a count on Sales_Monetary and Returns_Monetary.
However, when I do this the Products with 0 returns are counted as well.
In order to solve this issue I put WHERE Returns_Monetary > 0.
Unfortunately, with this condition the Sales_Monetary are also not counted.

Select 
Product, 
count(Sales_Monetary) AS Sold_Items
count(Returns_Monetary) AS Returned_Items,
count(Returns_Monetary) / count(Sales_Monetary) AS Return_Rate_Items
FROM Sales
WHERE Returns_Monetary > 0
GROUP BY 1;

What do I need to change in my query to make it work?

GMB :

However, when I do this the Products with 0 returns are counted as well.

Here is one way to only count in Returns_Monetary that are greater than 0:

select 
    Product, 
    count(Sales_Monetary) AS Sold_Items
    sum(Returns_Monetary > 0) AS Returned_Items,
    sum(Returns_Monetary > 0) / count(Sales_Monetary) AS Return_Rate_Items
from Sales
group by 1;

sum(Returns_Monetary > 0) increases by 1 for every Returns_Monetary that is greater than 0.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=8504&siteId=1