【问题标题】:Group by month in SQLite在 SQLite 中按月分组
【发布时间】:2020-02-10 20:41:24
【问题描述】:

我有一个包含交易的 SQLite 数据库,每个交易都有一个 price 和一个 transDate

我想检索按月分组的交易总和。检索到的记录应如下所示:

Price    month
230        2
500        3
400        4

【问题讨论】:

  • 表格的列有哪些?

标签: sql sqlite group-by


【解决方案1】:

当你按 MONTH 分组时总是很好,它也应该检查 YEAR

select SUM(transaction) as Price, 
       DATE_FORMAT(transDate, "%m-%Y") as 'month-year' 
       from transaction group by DATE_FORMAT(transDate, "%m-%Y");

对于 SQLITE

select SUM(transaction) as Price, 
       strftime("%m-%Y", transDate) as 'month-year' 
       from transaction group by strftime("%m-%Y", transDate);

【讨论】:

  • 如果您使用的是 android,这可能会有所帮助 strftime('%m-%Y', transDate, 'unixepoch')
  • 对于 SQlite 它对我有用,你使用 GROUP BY month-year
【解决方案2】:

您可以在月初分组:

select  date(DateColumn, 'start of month')
,       sum(TransactionValueColumn)
from    YourTable
group by 
        date(DateColumn, 'start of month')

【讨论】:

    【解决方案3】:

    尝试以下方法:

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

    使用 SQLite 文档中的 corresponding page 以供将来参考。

    【讨论】:

      【解决方案4】:
      SELECT
          SUM(Price) as Price, strftime('%m', myDateCol) as Month
      FROM
          myTable
      GROUP BY
          strftime('%m', myDateCol)
      

      【讨论】:

      • 有效,但可能会将 2009 年 3 月的值与 2010 年 3 月第 3 个月的值相加
      【解决方案5】:

      这是另一种形式:

      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】:

        在 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');
        

        【讨论】:

          【解决方案7】:

          另一种方法是从列中提取年份和月份并按它们分组。假设格式为 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);
          

          【讨论】:

            猜你喜欢
            • 2012-02-20
            • 2020-02-21
            • 2017-04-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多