I have a table that has multiple payments occuring on different dates each month. I would like the query to return a row for each individual payment and in that same row return the SUM of all payments for that month/year.
My table structure is:
tbl_or_Distri
`id` int(11) NOT NULL AUTO_INCREMENT,
`investment_id` int(11) NOT NULL,
`inv_distri_id` int(11) NOT NULL,
`trade_date` datetime NOT NULL,
`pay_date` datetime NOT NULL,
`amount` double NOT NULL,
`perc_return` double NOT NULL,
PRIMARY KEY (`id`),
My current inner query is:
SELECT
`investment_id`,
SUM(`perc_return`) as perc_return,
SUM(`capital_return`) as capital_return,
SUM(amount) as TotalAmount,
CONCAT(MONTH(pay_date), " ", YEAR(pay_date)) as short_date,
MONTH(pay_date) as pay_month,
YEAR(pay_date) as pay_year
FROM `tbl_or_distri`
WHERE investment_id=29
GROUP BY YEAR(pay_date), MONTH(pay_date)
The sum(amount), sum(perc_return), and short_date are the 3 records I need returned in each row of the main outer query. The outer query is:
SELECT
`investment_id`,
amount,
pay_date
FROM `tbl_or_distri`
WHERE investment_id=29
How can I combine these two queries into one? While maintaining good performance?
Thank you!
U could create a view for your inner query.
And then use the view in your outer query.
I don’t know what it does with performance but it would definitely work.