The COUNT aggregation function counts the number of rows in the table, so COUNT(id_receive) or COUNT(id_send), will make no difference in this case, as the table has the same number of rows in both cases.
To get a different number you must make two different queries, where each one will have a number of rows corresponding to the number of receipts or shipments as needed. Then you can join the two queries with a JOIN and have the desired result.
Code to create tables and add some examples:
CREATE TABLE IF NOT EXISTS `usuarios` (
`id` int NOT NULL,
`nome` varchar(40) NOT NULL,
`email` varchar(40) NOT NULL
);
CREATE TABLE IF NOT EXISTS `envios` (
`id` int NOT NULL,
`id_envia` int NOT NULL,
`id_recebe` int NOT NULL
);
INSERT INTO usuarios (id, nome, email) VALUES (1, "José", "[email protected]");
INSERT INTO usuarios (id, nome, email) VALUES (2, "Ricardo", "[email protected]");
INSERT INTO usuarios (id, nome, email) VALUES (3, "Gabriel", "[email protected]");
INSERT INTO envios (id, id_envia, id_recebe) VALUES (1, 1, 2);
INSERT INTO envios (id, id_envia, id_recebe) VALUES (2, 1, 2);
INSERT INTO envios (id, id_envia, id_recebe) VALUES (3, 1, 3);
INSERT INTO envios (id, id_envia, id_recebe) VALUES (1, 2, 1);
INSERT INTO envios (id, id_envia, id_recebe) VALUES (1, 3, 1);
Query calculating different numbers of submissions and receipts:
SELECT recebidos.id, recebidos.numeroRecebe, enviados.numeroEnvia
FROM
(SELECT usuarios.id, COUNT(envios.id_recebe) AS numeroRecebe
FROM usuarios LEFT JOIN envios ON (usuarios.id = envios.id_recebe)
GROUP BY usuarios.id) recebidos
JOIN
(SELECT usuarios.id, COUNT(envios.id_envia) AS numeroEnvia
FROM usuarios LEFT JOIN envios ON (usuarios.id = envios.id_envia)
GROUP BY usuarios.id) enviados
ON (recebidos.id = enviados.id)
You can test that it works.
Caio, could you solve? In case you haven’t solved, the database is Sql Server?
– Developer
It worked or you still need help?
– Ruberlei Cardoso