【问题标题】:SQL combining GROUP BY and SUM组合 GROUP BY 和 SUM 的 SQL
【发布时间】:2009-10-28 20:26:17
【问题描述】:

我需要有关 SQL 的帮助。我有一个这样的 sqlite 表;

CREATE TABLE mytable (datetime DATE, type TEXT, amount REAL)

我需要一个查询来汇总每种类型和年月的金额(正如您所看到的,由于数据可以跨越几年,所以也提取了年份)。我已经半途而废了,但是我对 SQL 有点生疏了。

sqlite> SELECT strftime('%Y',datetime) AS year, strftime('%m',datetime) AS month, type, amount FROM mytable ;

2009|06|Type1|-1000.0
2009|06|Type1|-100.0
2009|06|Type2|-100.0
2009|07|Type1|-214.91
2009|07|Type2|-485.0

我在上面的查询中尝试了多种 SUM 和 GROUP BY 的组合,但它们都没有达到我想要的效果。我想要的是这样的结果:

2009|06|Type1|-1100.0
2009|06|Type2|-100.0
2009|07|Type1|-214.91
2009|07|Type2|-485.0

是的,type 应该是外键,我简化了一些事情以便更容易提出问题:)

【问题讨论】:

  • 每年总结还是每月总结?
  • 对不起,年月,现在澄清。

标签: sql sqlite


【解决方案1】:
SELECT strftime('%Y',datetime) AS year, 
       strftime('%m',datetime) AS month, 
       type, 
       Sum(amount) As Amount 
FROM mytable 
Group By 1, 2, 3

注意

某些数据库不支持按索引分组,因此您必须这样做。

SELECT strftime('%Y',datetime) AS year, 
       strftime('%m',datetime) AS month, 
       type, 
       Sum(amount) As Amount 
FROM mytable 
Group By strftime('%Y',datetime), 
       strftime('%m',datetime), 
       type

【讨论】:

  • 对 GROUP BY(和 ORDER BY)使用序数时要小心 - 如果列顺序发生变化,就会产生影响。
  • 是的,懒惰会回来咬你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
  • 2012-09-18
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多