使用两个 group by 和一个 select 语句

use*_*724 4 mysql select group-by

我有两张桌子

  1. 带有列 id、年、月的日期
  2. 带有列 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)
Run Code Online (Sandbox Code Playgroud)

并获得其他值:

  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
Run Code Online (Sandbox Code Playgroud)

但我需要通过一个查询来完成它。有没有另一种方法来检索这个数据集?是否可以在同一个 select 语句中以两种方式使用 group by?

Joh*_*Woo 9

这是您要找的人吗?

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`
Run Code Online (Sandbox Code Playgroud)

所述第一子查询是通过获取量的总和和所述第二子查询获取仪器的总和。他们的结果将被加入,以便连续获得 totalAmount 和 totalInstrument。