Mysql 使用两个GROUPBY和一个select语句
我有两张桌子Mysql 使用两个GROUPBY和一个select语句,mysql,select,group-by,Mysql,Select,Group By,我有两张桌子 列id为的日期,年,月 具有列id、金额、类型、收入、工具的交易记录 类型只能是借方或贷方,工具可以是信用卡等任何方法 我需要的是得到一个查询,其中选择年、月、类型、工具以及按类型和工具分组的“金额”总和,以及按年和月分组的收入总和 我可以使用两个不同的查询获取值 例如: 要获得按年份和月份分组的收入总和,请执行以下操作: select sum(T.income) as total from transaction as T, date as D where D.
select sum(T.income) as total
from transaction as T, date as D
where D.id = T.id
group by D.month, D.year)
以及获取其他值:
select D.year, D.month,
T.type, T.instrument, sum(T.amount) as sumAmount,T.income
from date as D, transaction as T
where D.id=T.id,
group by T.instrument, T.type
但我需要通过一个查询来完成它。是否有其他方法检索此数据集?可以在同一select语句中以两种方式使用group by吗?这就是您要查找的语句吗
SELECT tableA.ID, tableA.`Year`, tableA.`Month`,
tableA.`Type`, tableA.instrument,
tableA.totalAmount, tableB.totalInstrument
FROM
(
SELECT a.ID, a.`Year`, a.`Month`,
b.`Type`, b.instrument,
SUM(b.`amount`) totalAmount
FROM `date` a
INNER JOIN `transactions` b
ON a.ID = b.id
GROUP BY b.`Type
) tableA
INNER JOIN
(
SELECT a.ID, a.`Year`, a.`Month`,
b.`Type`, b.instrument,
SUM(b.`instrument`) totalInstrument
FROM `date` a
INNER JOIN `transactions` b
ON a.ID = b.id
GROUP BY a.`Year`, a.`Month`
) tableB ON tableA.ID = tableB.ID AND
tableA.`Year` = tableB.`Year` AND
tableA.`Month` = tableB.`Month`
第一个子查询通过获取金额之和,第二个子查询获取工具之和。它们的结果将合并在一起,以便获得一行中的totalAmount和totalInstrument。为什么需要在一个语句中执行此操作?您是如何使用结果的?是的,此查询有帮助。谢谢。它回答了你的问题吗?:)@user1500724:如果它回答了你的问题,你能不能请吴宇森的回答作为正确答案,这样它将有助于未来的访客?