我想根据日期时间过滤数据(行)

时间:2019-07-15 04:54:55

标签: asp.net sql-server database

我想基于datetime列过滤数据(行)。例如,当日期时间列是月份的最后日期(31/30)在00:00:00.000时间时,我想要数据(行)。

我有一个数据文件,该数据文件的一列具有类似于2018-10-28 00:56:98.003的数据,并且想要该月的最后日期为00:00:00.000的数据。 the image show the sample database which i have and i have to filter the data according to TimeCol(column name) that is on the last date of month(31,30,28) 然后在过滤数据后,我想对其执行一些算术运算

2 个答案:

答案 0 :(得分:0)

我认为 EOMONTH 功能是您所需要的:

         DROP TABLE IF EXISTS #temp

         CREATE TABLE #temp (dtDatetime DATETIME NOT NULL)

         INSERT #temp
         SELECT '20190112 00:00:00.000' UNION ALL
         SELECT '20190131 01:00:00.000' UNION ALL
         SELECT '20190131 00:00:00.000' UNION ALL
         SELECT '20190214 00:00:00.000' UNION ALL
         SELECT '20190228 00:00:00.000' UNION ALL
         SELECT '20190228 01:00:00.000' UNION ALL
         SELECT '20190317 00:00:00.000' UNION ALL
         SELECT '20190331 00:00:00.000' UNION ALL
         SELECT '20190331 01:00:00.000' 


         SELECT * FROM #temp
         WHERE dtDatetime = EOMONTH(dtDatetime)

returns:

 - 2019-01-31 00:00:00.000 
 - 2019-02-28 00:00:00.000
 - 2019-03-31 00:00:00.000

答案 1 :(得分:0)

这很容易,此步骤将使您知道当前行的当前月末。然后使用LINQ-> Where(..)扩展方法进行过滤。 这是示例:

public class Row
{
    public string Id { get; set; } = Guid.NewGuid().ToString();
    public string Data { get; set; }
    public DateTime DateTime { get; set; }
}

List<Row> rows = new List<Row>
{
    new Row
    {
        Data = "Data 1",
        DateTime = new DateTime(2019,1,21,21,10,0)
    },

    new Row
    {
        Data = "Data 2",
        DateTime = new DateTime(2019,1,1,23,0,0)
    },

    new Row
    {
        Data = "Data 3",
        DateTime = new DateTime(2019,2,28,0,0,0)
    },

    new Row
    {
        Data = "Data 4",
        DateTime = new DateTime(2019,3,14,13,15,12)
    },

    new Row
    {
        Data = "Data 5",
        DateTime = new DateTime(2019,07,31,21,10,0)
    },

    new Row
    {
        Data = "Data 6",
        DateTime = new DateTime(2019,06,30,0,0,0)
    }
};

List<Row> filteredRows = rows.Where(row =>
{
    //This functions used to get the last day in a month
    int endOfMonth = DateTime.DaysInMonth(row.DateTime.Year, row.DateTime.Month);
    return (
          row.DateTime.Day == endOfMonth &&
          row.DateTime.Hour == 0 &&
          row.DateTime.Minute == 0 &&
          row.DateTime.Second == 0 &&
          row.DateTime.Millisecond == 0
    );
}).ToList();

filteredRws变量将包含数据->“数据3”和“数据6”。

此致

米尔扎