我有一个包含交易的SQLite数据库,每个交易都有价格和 transDate 。
我想检索按月分组的交易总和。检索到的记录应如下所示:
Price month
230 2
500 3
400 4
答案 0 :(得分:22)
当你按MONTH分组时它总是好的,它也应该检查YEAR
select SUM(transaction) as Price,
DATE_FORMAT(transDate, "%m-%Y") as 'month-year'
from transaction group by DATE_FORMAT(transDate, "%m-%Y");
FOR SQLITE
select SUM(transaction) as Price,
strftime("%m-%Y", transDate) as 'month-year'
from transaction group by strftime("%m-%Y", transDate);
答案 1 :(得分:2)
SELECT
SUM(Price) as Price, strftime('%m', myDateCol) as Month
FROM
myTable
GROUP BY
strftime('%m', myDateCol)
答案 2 :(得分:1)
您可以在月初分组:
select date(DateColumn, 'start of month')
, sum(TransactionValueColumn)
from YourTable
group by
date(DateColumn, 'start of month')
答案 3 :(得分:1)
尝试以下方法:
SELECT SUM(price), strftime('%m', transDate) as month
FROM your_table
GROUP BY strftime('%m', transDate);
使用SQLite文档中的corresponding page以供将来参考。
答案 4 :(得分:0)
在Sqlite中,如果您以unixepoch格式存储日期,则以秒为单位:
select count(myDate) as totalCount,
strftime('%Y-%m', myDate, 'unixepoch', 'localtime') as yearMonth
from myTable group by strftime('%Y-%m', myDate, 'unixepoch', 'localtime');
如果您以unixepoch格式存储日期(以毫秒为单位)除以1000:
select count(myDate/1000) as totalCount,
strftime('%Y-%m, myDate/1000, 'unixepoch', 'localtime') as yearMonth
from myTable group by strftime('%Y-%m, myDate/1000, 'unixepoch', 'localtime');
答案 5 :(得分:0)
另一种形式:
SELECT SUM(price) AS price,
STRFTIME('%Y-%m-01', created_at) as created_at
FROM records
GROUP BY STRFTIME('%Y-%m-01', created_at);
答案 6 :(得分:0)
另一种方法是从列中对年份和月份进行子串并按它们分组。假设格式类似于 2021-05-27 12:58:00,您可以减去前 7 位数字:
SELECT
substr(transDate, 1, 7) as YearMonth
SUM(price) AS price
FROM
records
GROUP BY
substr(transDate, 1, 7);