我有一个SQLite数据库结构如下:
ID Date Time Cost
"1" "2016-05-14" "17:39:35.925973" "1.98"
"2" "2016-05-14" "17:39:54.181083" "2.84"
"3" "2016-05-14" "17:40:26.408492" "2.99"
"4" "2016-05-14" "17:41:28.197353" "3.39"
"25" "2016-05-19" "14:44:27.235790" "2.5"
"26" "2016-05-19" "14:46:35.177696" "1.58"
"27" "2016-05-19" "14:49:12.902651" "0.1"
"28" "2016-05-20" "21:35:32.446997" "2.25"
我想把费用按月和年加起来,不考虑日期。
我在python中做这个,但是我甚至不知道选择月份和年份的sqlite代码。
我试过这个代码:
def SumByMonth():
usrDate = raw_input('Enter yymm: ')
dateyear = datetime.datetime.strptime(usrDate, "%y%m").date()
month_sql = '''SELECT cost FROM Finance WHERE strftime('%m%y', date) = ( ? )'''
month_price = [t[0] for t in cur.execute(month_sql, ( dateyear,) )]
sum_total = sum(month_price)
print 'sum is for', dateyear,'is', sum_total
我得到的所有结果都是sum is for 2016-05-01 is 0
,所以它看起来是在选择当月的第一天,而没有提供一天。我如何选择月份和年份?
谢谢
SQLite没有2位数年份的格式说明符。参考:https://www.sqlite.org/lang_datefunc.html
并且,正如@DanielRoseman提到的:
- 你混淆了年份和月份,
- 你不必要地将字符串转换为日期时间。
而不是做的事:
def SumByMonth():
yyyymm = raw_input('Enter yyyymm: ')
month_sql = '''SELECT cost FROM Finance WHERE strftime('%Y%m',date) = ?'''
month_price = [t[0] for t in cur.execute(month_sql,(yyyymm,))]
sum_total = sum(month_price)
print 'sum is for', yyyymm,'is', sum_total
更简洁的做法是:
def SumByMonth():
yyyymm = raw_input('Enter yyyymm: ')
month_sql = '''SELECT SUM(cost) FROM Finance WHERE strftime('%Y%m',date) = ?'''
sum_total = cur.execute(month_sql,(yyyymm,)).fetchone()[0]
print 'sum is for', yyyymm,'is', sum_total