Group by month in SQLite

前端 未结 6 695
礼貌的吻别
礼貌的吻别 2020-12-16 14:17

I have an SQLite database which contains transactions, each of them having a price and a transDate.

I want to retrieve the sum of the transactions

相关标签:
6条回答
  • 2020-12-16 14:23

    This another form:

    SELECT SUM(price) AS price,
    STRFTIME('%Y-%m-01', created_at) as created_at
    FROM records
    GROUP BY STRFTIME('%Y-%m-01', created_at);
    
    0 讨论(0)
  • 2020-12-16 14:24
    SELECT
        SUM(Price) as Price, strftime('%m', myDateCol) as Month
    FROM
        myTable
    GROUP BY
        strftime('%m', myDateCol)
    
    0 讨论(0)
  • 2020-12-16 14:25

    it is always good while you group by MONTH it should check YEAR also

    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);
    
    0 讨论(0)
  • 2020-12-16 14:36

    In Sqlite, if you are storing your date in unixepoch format, in seconds:

    select count(myDate) as totalCount, 
    strftime('%Y-%m', myDate, 'unixepoch', 'localtime') as yearMonth
    from myTable group by strftime('%Y-%m', myDate, 'unixepoch', 'localtime');
    

    If you are storing the date in unixepoch format, in milliseconds, divide by 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');
    
    0 讨论(0)
  • 2020-12-16 14:37

    Try the following:

    SELECT SUM(price), strftime('%m', transDate) as month
    FROM your_table
    GROUP BY strftime('%m', transDate);
    

    Use the corresponding page in SQLite documentation for future references.

    0 讨论(0)
  • 2020-12-16 14:44

    You can group on the start of the month:

    select  date(DateColumn, 'start of month')
    ,       sum(TransactionValueColumn)
    from    YourTable
    group by 
            date(DateColumn, 'start of month')
    
    0 讨论(0)
提交回复
热议问题