1

Boa noite, preciso fazer uma consulta na tabela abaixo:

tabela

Mas que me traga o resultado de quantos type = E , type = S agrupado por mês, esse resultado eu vou jogar em um gráfico que vai exibir por mês quantas entrada e saída;

Segue codigo pra criar a tabela :

CREATE TABLE `movements` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_product` int(11) NOT NULL,
  `id_user` int(11) NOT NULL,
  `type` enum('S','E') NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `movements_product_idx` (`id_product`),
  KEY `movements_user_idx` (`id_user`),
  CONSTRAINT `movements_product` FOREIGN KEY (`id_product`) REFERENCES `product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `movements_user` FOREIGN KEY (`id_user`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;

Tentei esse código, está agrupando por mês mas não sei quantas type='S' ou 'E' tive nesse mês;

select count(id)Total, DATE_FORMAT (`date`,'%b') AS `mes` from movements group by month(date);

Se alguém souber como faz agradeço...

1 Resposta 1

3

Se entendi corretamente, creio que:

SELECT DATE_FORMAT(`date`,'%b') AS `mes`, 
       SUM(CASE WHEN Type = 'E' THEN 1 ELSE 0 END) AS TypeE, 
       SUM(CASE WHEN Type = 'S' THEN 1 ELSE 0 END) AS TypeS 
FROM movements 
GROUP BY month(date);

possa atende-lo.

1
  • Cara valeu, isso mesmo, funcionou aqui! 3/10/2020 às 22:00

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .