T-SQL:将时间四舍五入到15分钟,但仅在15分钟后5分钟之后

时间:2019-07-16 16:37:40

标签: sql tsql

我有一个带有日期时间字段的表。我正在尝试以15分钟为间隔四舍五入时间。但是对于非标准的数学舍入规则,如果超过15分钟间隔超过5分钟,则会进行舍入。

例如

如果06:05向下舍入到06:00

如果06:06向上舍入到06:15

如果06:20向下舍入到06:15

如果06:21舍入到06:30 等等。

我设法在这里T-SQL: Round to nearest 15 minute interval舍入到最近的15分钟,但这使用了数学舍入法,这意味着06:07仍将舍入到06:00,而不是舍入到06:15。

下面我要去的代码:

cast(datepart(hour, getdate()) + datepart(minute, getdate()) / 60.00 as decimal(5, 2))

1 个答案:

答案 0 :(得分:3)

只需使用一些约会技巧即可。

此代码将为您提供评估时间的最佳时间(通过将自SQL中的0日期起的小时数加起来有效地消除了分钟数):

    public static void main(String[] args) {
        Path filePath = Path.of("C:\\tmp\\anno");
        if (!Files.exists(filePath)) {
            System.out.println("File does not exist at '" + filePath + "'");
            System.exit(1);
        }

        List<HashMap<String, String>> annotations = new ArrayList<HashMap<String, String>>();
        try {
            List<String> annoFile = Files.readAllLines(filePath);
            List<String> headers = Arrays.asList(annoFile.remove(0).split("\\|"));
            headers.forEach(System.out::println);

            while (annoFile.size() > 0) {
                List<String> rowValues = Arrays.asList(annoFile.remove(0).split("\\|"));
                HashMap<String, String> annotation = new HashMap<>();
                for (int i = 0; i < headers.size(); i++) {
                    if (rowValues.size() >= i) {
                        annotation.put(headers.get(i).strip(), rowValues.get(i).strip());
                    }
                }
                annotations.add(annotation);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

从那里,您需要一个select dateadd(hour, datediff(hour, 0, getdate()), 0) 表达式来评估所讨论的时间属于哪个小时的四分位数(此处只是一个片段):

CASE

将这两部分与 case when datepart(minute, dtm) > 50 then 60 when datepart(minute, dtm) > 35 then 45 when datepart(minute, dtm) > 20 then 30 when datepart(minute, dtm) > 5 then 15 else 0 end 放在一起,以决定我们要添加到该偶数小时标记的分钟数:

DATEADD

结果:

declare @dtms table (dtm datetime);
insert @dtms (dtm)
values ('2019-07-16T12:05:00'),
       ('2019-07-16T12:06:00'),
       ('2019-07-16T12:21:00'),
       ('2019-07-16T12:29:00'),
       ('2019-07-16T12:35:00'),
       ('2019-07-16T12:38:00'),
       ('2019-07-16T12:56:00')

select
  dtm,
  dateadd(minute, 
    case 
      when datepart(minute, dtm) > 50 then 60
      when datepart(minute, dtm) > 35 then 45
      when datepart(minute, dtm) > 20 then 30
      when datepart(minute, dtm) > 5  then 15
      else 0
    end, dateadd(hour, datediff(hour, 0, dtm), 0)) as rounded
from @dtms;