打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
sqlite3
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need help with SQL. I have an sqlite table like so;

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

I need a query which would sum up amount for each type AND year-month (as you can see the year is also extracted since the data can span several years). I've come to something half-way, but I'm a bit rusty on SQL.

sqlite> SELECT strftime('%Y',datetime) AS year, strftime('%m',datetime) AS month, type, amount FROM mytable ;2009|06|Type1|-1000.02009|06|Type1|-100.02009|06|Type2|-100.02009|07|Type1|-214.912009|07|Type2|-485.0

I've tried a number of combinations of SUM and GROUP BY on my query above but none of them does what I want. What I want is a result something like:

2009|06|Type1|-1100.02009|06|Type2|-100.02009|07|Type1|-214.912009|07|Type2|-100.0

Yes, type should be a foreign key, I simplified things to make it easier to ask the question :)

asked Oct 28 '09 at 20:26
pojo
1,48111631


 
sum up for each Year-Month or just for Month? –  Raj More Oct 28 '09 at 20:29

 
Sorry, year-month, clarified now. –  pojo Oct 28 '09 at 20:31

1 Answer

up vote 6 down vote accepted
SELECT strftime('%Y',datetime) AS year,        strftime('%m',datetime) AS month,        type,        Sum(amount) As Amount FROM mytable Group By 1, 2, 3

Note

Some DBs don't support group by index so you would have to do this.

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
answered Oct 28 '09 at 20:28
ChaosPandion
33k452101

2  
Careful when using ordinals for GROUP BY (and ORDER BY) - if the column order changes, there will be impact. –  OMG Ponies Oct 28 '09 at 20:32

 
Yes, laziness can come back to bite you. –  ChaosPandion Oct 28 '09 at 20:34

 
Many thanks, worked like a charm! –  pojo Oct 28 '09 at 20:36
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
定投指数到底能不能赚钱?Python 来告诉你答案
【转】关于Sqlite的日期比较方法
如果用python的方法删除N天前创建的文件? [
python获取当前时间
蓝桥杯|Python组第三题
sqlite时间函数及时间处理
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服