mysql - 将两个 group by 与一个 select 语句一起使用

标签 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)

并获取其他值:

  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/

相关文章:

python - 如何在 pandas 数据透视表上执行数学运算?

php - Magento 2 : Database user does not have enough privileges

mysql - 使用mysqlconnector ODBC从sql连接 Access 时连接失败

php - 保护网络服务器中的 PDF 不被公开访问

sql - 使用 Oracle 9i 将单个文本列列表转换为 2 列列表

mysql - PGError : ERROR: column "inboxes.id" must appear in the GROUP BY clause or be used in an aggregate function

sql - Postgres/ANSI SQL 系统如何将 'count' 聚合与 GROUP BY 字段相关联

php - 使用内爆将 HTML 表单 $_POST 数组插入 MySQL

ruby-on-rails - Rails collection_select 默认选择

Cakephp 选择具有相应值的数字列表