我有三张这样的表
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`)
)
实际上并不复杂。非常简单。
我有三个查询要查找
特定月份的收入总和:
select sum(amount) tot_inc from money.income ic where month(ic.date) = 02;
特定月份的支出总和:
select sum(amount) tot_exp from money.expenditure ex where month(ex.date) = 02;
特定类别特定月份的支出总和:
select sum(amount) tot_exp from money.expenditure ex where month(ex.date) = 02 and ex.categoryid = 3;
我有两个问题:
如何找出已经消失的总收入占特定月份总支出的百分比。基本上我想从查询1和2中找出(100 * tot_exp / tot_inc)但是如何在查询中写出来?
在此基础上,我想了解每个类别的支出在特定月份的贡献百分比。我知道它是分组和聚合和/或数学函数的组合,但我甚至无法开始可视化查询的编写方式。我怎样才能得到这些数字?
答案 0 :(得分:1)
SELECT
(100*(SELECT SUM(amount) tot_inc FROM money.income ic WHERE month(ic.date) = "02")/SUM(amount)) AS "Result"
FROM expenditure e
WHERE MONTH(ex.date) = "02"
GROUP BY CategoryID
HAVING result > 10
我认为会是这样的