Sql server SQL Server:根据特定的时间戳从表中选择数据

Sql server SQL Server:根据特定的时间戳从表中选择数据,sql-server,database,Sql Server,Database,我有一个表,它以一分钟的时间戳相互存储数据,我想创建一个select命令,该命令将从请求时间段的每小时:59分钟标记获取数据,例如从2020年1月1日到2020年2月1日 我怎么能这样做?我附加了该表中的数据示例,select命令将引用该数据示例: 这个 我想你在找这样的东西。用通俗易懂的语言表示,对于开始日期到结束日期的范围,选择测试表的每小时摘要统计信息,而不跳过任何小时 桌子 资料 质疑 这将从每小时:59分钟的标记中获取数据,这意味着什么?对于给定的xx值,是否只需要xx:59:00和x

我有一个表,它以一分钟的时间戳相互存储数据,我想创建一个select命令,该命令将从请求时间段的每小时:59分钟标记获取数据,例如从2020年1月1日到2020年2月1日

我怎么能这样做?我附加了该表中的数据示例,select命令将引用该数据示例:

这个


我想你在找这样的东西。用通俗易懂的语言表示,对于开始日期到结束日期的范围,选择测试表的每小时摘要统计信息,而不跳过任何小时

桌子

资料

质疑


这将从每小时:59分钟的标记中获取数据,这意味着什么?对于给定的xx值,是否只需要xx:59:00和xx+1:00:00之前的数据?在示例数据中没有行,因为在第59分钟没有行。如果这是您想要的,这似乎是一个奇怪的要求,那么DATEPART和MINUTE函数有什么问题?如果那不是你想要的,你想要什么?你试过什么,为什么不奏效?花点时间以文本形式(最好是DDL和DML语句)发布示例数据,并包含预期结果。是否希望在指定的日期/时间范围内每小时显示最后一行?
SELECT * FROM table WHERE DATEPART(MINUTE, 'your_datetime') = '59'
drop table if exists test_table;
go
create table test_table(
  ID        int primary key not null,
  date_dt   datetime,
  INP3D     decimal(4, 3),
  ID_device varchar(20));
insert test_table(ID, date_dt, INP3D, ID_device) values
(1, '2020-08-21 13:44:34.590', 3.631, 'A1'),
(2, '2020-08-21 13:44:34.590', 1.269, 'A1'),
(3, '2020-08-21 13:44:34.590', 0.131, 'A1'),
(4, '2020-08-21 13:44:34.590', 8.169, 'A1');
--select * from test_table;
insert test_table(ID, date_dt, INP3D, ID_device) values
(5, '2020-08-21 11:44:34.590', 3.631, 'A1'),
(6, '2020-08-21 02:44:34.590', 1.269, 'A1'),
(7, '2020-08-22 11:44:34.590', 0.131, 'A1'),
(8, '2020-08-22 01:44:34.590', 8.169, 'A1');
declare
  @start_dt         datetime='2020-08-21',
  @end_dt           datetime='2020-08-22';

;with 
hours_cte as (
    select hours_n
    from 
    (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),
            (13),(14),(15),(16),(17),(18),(19),(20),(21),(22),(23),(24)) v(hours_n)),
days_cte as (
    select dateadd(d, hours_n-1, @start_dt) calc_day from hours_cte where hours_n<=datediff(d, @start_dt, @end_dt)+1)
select
  dc.calc_day,
  hc.hours_n,
  count(*) row_count,
  isnull(avg(INP3D), 0) inp3d_avg,
  isnull(sum(INP3D+0000.000),0) inp3d_sum
from days_cte dc
     cross join hours_cte hc
     left join test_table t on t.date_dt between dateadd(hour, (hours_n-1), dc.calc_day) 
                                            and dateadd(hour, (hours_n), dc.calc_day) 
group by
  dc.calc_day,
  hc.hours_n
order by
  1,2;