【问题标题】:Use two group by with one select statement通过一个 select 语句使用两个 group by
【发布时间】:2012-08-03 06:08:06
【问题描述】:

我有两张桌子

  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?

【问题讨论】:

  • 为什么需要在一份声明中做到这一点?您如何使用结果?

标签: mysql select group-by


【解决方案1】:

这是你要找的那个吗?

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 : 如果它回答了你的问题,你能否请 John Woo 的回答作为正确答案,这样对以后的访问者有帮助?
猜你喜欢
  • 1970-01-01
  • 2011-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
  • 2022-01-08
相关资源
最近更新 更多