I have three tables like this
CREATE TABLE `money`.`categories` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`Title` text NOT NULL,
PRIMARY KEY (`ID`)
)
CREATE TABLE `money`.`expenditure` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`Purpose` text NOT NULL,
`Amount` bigint(20) unsigned NOT NULL,
`Date` datetime NOT NULL,
`CategoryID` bigint(20) unsigned NOT NULL,
PRIMARY KEY (`ID`),
KEY `FK_expenditure_1` (`CategoryID`),
CONSTRAINT `FK_expenditure_1` FOREIGN KEY (`CategoryID`) REFERENCES `categories` (`ID`)
)
CREATE TABLE `money`.`income` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`Source` text NOT NULL,
`Amount` bigint(20) unsigned NOT NULL,
`Date` datetime NOT NULL,
PRIMARY KEY (`ID`)
)
It is actually not complicated at all. Very simple.
I have three queries to find
-
the sum of income for a particular month:
select sum(amount) tot_inc from money.income ic where month(ic.date) = 02; -
sum of expenditure for a particular month:
select sum(amount) tot_exp from money.expenditure ex where month(ex.date) = 02; -
sum of expenditure for a particular month in a particular category:
select sum(amount) tot_exp from money.expenditure ex where month(ex.date) = 02 and ex.categoryid = 3;
I have two questions:
-
How can I find out the percentage of total income that has gone away as total expenditure for a particular month. Basically I want to find out (100*tot_exp/tot_inc) from queries 1 and 2. but how can I write it in query?
-
Building on top of that, I want to find out how much percentage each category of expenditure contributed to ina particular month. I understand it is a combination of group by and aggregate and/or math functions but I can’t even begin to visualize how the query should be written. How can I get these numbers?
I think it would be something like this