我有两个表
- 带有 id、年、月列的日期
- 具有列 id、金额、类型、收入、工具的交易
类型只能是借方或贷方,工具可以是信用卡等任何方式。
我需要的是获得一个查询,其中选择年、月、类型、工具和按类型和工具分组的“金额”总和以及按年和月分组的收入总和。
我可以使用两个不同的查询来获取值
例子:
获取按年月分组的收入总和:
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。
关于mysql - 将两个 group by 与一个 select 语句一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11825427/