One solution is to make two queries and join them with a LEFT JOIN. See example:
CREATE DATABASE example;
use example;
CREATE TABLE sales (id INT, product_name VARCHAR(100), VALOR INT);
INSERT INTO sales (id,product_name,valor)
VALUES (1,'CAFÉ',1200);
INSERT INTO sales (id,product_name,valor)
VALUES (2,'cerveja',500);
INSERT INTO sales (id,product_name,valor)
VALUES (2,'macarrao',3000);
INSERT INTO sales (id,product_name,valor)
VALUES (3,'vinho',12500);
INSERT INTO sales (id,product_name,valor)
VALUES (4,'azeitona',250);
SELECT id, total, COALESCE(totalm1000,0) as totalm1000
FROM
(SELECT id, COUNT(DISTINCT(product_name)) as total
FROM example.sales
GROUP BY id) as T1
LEFT JOIN
(SELECT id as id2, COUNT(DISTINCT(product_name)) as totalm1000
FROM example.sales
WHERE valor>1000
GROUP BY id2) as T2
ON id=id2
Returns:
+------+-------+------------+
| id | total | totalm1000 |
+------+-------+------------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 1 | 1 |
| 4 | 1 | 0 |
+------+-------+------------+
The first query returns the total products sold per id, the second returns the total products sold with value greater than 1000 per id.
Thank you so much for your help Lucas, it worked that way. I’m two days trying to solve this problem.
– Pedro Souza
who gave the downvote care in justifying?
– Lucas