在sqlite中按日期时间列与月份和年份进行分组

问题描述 投票:0回答:1

我正在使用 xamarin 表单。我在 SQLite group by 中的日期时间字段上遇到一些问题。 我正在使用下表:

public class DataTable
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
    public int WorkOrderId { get; set; }
    public Nullable<DateTime> TargetDateTime { get; set; }
}

我的上表数据如下:

ID  WorkOrderId     TargetDateTime 
1   835     2018-08-16 00:00:00.000
2   836     2018-08-27 00:00:00.000
3   837     2018-09-18 00:00:00.000
4   838     2018-09-29 00:00:00.000
5   839     2018-10-15 00:00:00.000
6   840     2018-11-19 00:00:00.000

我想按 TargetDateTime 列的月份和年份对该表进行分组,如下所示:

MonthYear   count
07-2018     2
08-2018     2
09-2018     1
10-2018     1

出于查看此表的目的,我使用以下内容:

public class DataTableSummary
    {
        public string YearMonth { get; set; }
        public string MonthYear { get; set; }
        public int RecordCount { get; set; }

    }

var com = conn.Query<DataTableSummary>("SELECT strftime('%m-%Y',TargetDateTime) as YearMonth,count(*) as RecordCount FROM DataTable group by strftime('%m-%Y',TargetDateTime)");

但是它不起作用。谁能帮我解决这个问题。

c# sqlite
1个回答
0
投票

假设

TargetDateTime
是字符串类型,格式为
yyyy-mm-dd hh:mm:ss

strftime

select
  strftime('%m-%Y', TargetDateTime) as YearMonth,
  count(1) as RecordCount
from DataTable
group by YearMonth
$ sqlite3
sqlite> select strftime('%m-%Y', '2023-12-20 12:34');
12-2023

substr

select
  substr(TargetDateTime, 0, 8) as YearMonth,
  count(1) as RecordCount
from DataTable
group by YearMonth
$ sqlite3
sqlite> select substr('2023-12-20 12:34', 0, 8);
2023-12

另请参阅如何在 SQLite 中按月分组

© www.soinside.com 2019 - 2024. All rights reserved.