I am trying to get the total amount per month from 2 tables Here is my query
SELECT
date_format(items.date, '%M %Y') as month,
COALESCE(SUM(items.amount), 0) as Rreceived,
COALESCE(SUM(issued_items.amount), 0) as Issued,
items.currency
FROM
items
LEFT JOIN
issued_items
ON date_format(items.date, '%Y-%m')=date_format(issued_items.date, '%Y-%m')
AND items.currency=issued_items.currency
GROUP BY
date_format(items.date, '%Y-%m')
Rreceived amount should be 100, but I am getting 200. Can you please help me correct the query?
CREATE TABLE IF NOT EXISTS issued_items (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`purpose` varchar(255) NOT NULL,
`amount` decimal(25,2) NOT NULL,
`currency` varchar(3) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=7;
INSERT INTO issued_items (`id`,`date`,`purpose`,`amount`,`currency`) VALUES
(5, '2013-05-13', 'Test', 100.00, 'USD'),
(6, '2013-05-13', 'Test', 100.00, 'USD');
CREATE TABLE IF NOT EXISTS items (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`purpose` varchar(255) NOT NULL,
`currency` varchar(3) NOT NULL,
`amount` decimal(25,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2;
INSERT INTO items (`id`,`date`,`purpose`,`currency`,`amount`) VALUES
(1, '2013-05-13', 'Test', 'USD', 100.00);
Requirement logic extension:
I also need to represent records from issued_items even if there is no record for the month-period in the items table.
Add this row to issued_items:
(7, '2013-07-01', 'Test', 100.00, 'USD')
dateso regardless of the join type you will get that result. I think you should look into redesign your schema, probably add item_id to issued_items.