I am stuck with a query because i want to grouping the value "clv_cuota".
These are my data:
CREATE TABLE cuotas (
id_cuota int(11) NOT NULL,
clv_cuota int(11) DEFAULT NULL,
debe decimal(10,2) DEFAULT '0.00',
haber decimal(10,2) DEFAULT '0.00',
PRIMARY KEY (id_cuota)
) ENGINE=INNODB DEFAULT CHARSET=latin1;
CREATE VIEW Balances AS
SELECT m.`id_cuota`, m.`clv_cuota`, m.`debe`, m.`haber`,
(select sum(debe) - sum(haber) FROM cuotas m2
where m2.id_cuota <= m.id_cuota
) as balance
FROM `cuotas` m
GROUP BY m.clv_cuota, m.`id_cuota` DESC;
INSERT INTO `cuotas` (`id_cuota`, `clv_cuota`, `debe`, `haber`) VALUES
('18', '115', '100.00', '0.00'),
('19', '116', '100.00', '0.00'),
('20', '115', '50.00', '0.00'),
('21', '115', '0.00', '150.00'),
('23', '116', '50.00', '0.00'),
('24', '116', '20.00', '0.00');
the result of the query is:
id_cuota clv_cuota debe haber balance
21 115 0 150 100
20 115 50 0 250
18 115 100 0 100
24 116 20 0 170
23 116 50 0 150
19 116 100 0 200
It is grouped well but the result of the balance is not correct
I need a result like this
id_cuota clv_cuota debe haber balance
21 115 0 150 0
20 115 50 0 150
18 115 100 0 100
24 116 20 0 170
23 116 50 0 150
19 116 100 0 100
thanks in advance.