我的表格如下:
表1: 注意:这个表实际上非常大,有更多列(20ish)和行(以百万计)
| Time | tmp | productionID |
| 10:00:00 | 2.2 | 5 |
| 10:00:05 | 5.2 | 5 |
| 10:00:11 | 7.4 | 5 |
| ...... | 3.2 | 5 |
| 10:10:02 | 4.5 | 5 |
注意:Time是一个varchar,所以我假设我需要做这样的事情:
CONVERT(VARCHAR(8), DATEADD(mi, 10, time), 114)
我需要做的是:
select time, tmp
from mytable
where productionid = somevalue
and time = first_time_stamp associated to some productionID(ie. 10:00:00 table above)
time = 10 minutes after the first_time_stamp with some productionID
time = 20 minutes after the first_time_stamp with some productionID
...25, 30, 40, 60, 120, 180 minutes
我希望这是有道理的。我不确定这样做的正确方法是什么。我的意思是我想到了以下过程: - 选择第一个时间戳(带有一些productionID) - 到那个时候10分钟, -add 20分钟等..然后使用数据透视表并使用连接链接到表1 必须有一个更简单的方法。
提前感谢您的专业知识。
预期的样本输出:
| Time | tmp
| 10:00:00 | 2.2
| 10:10:02 | 4.5
| 10:20:54 | 2.3
| 10:30:22 | 5.3
答案 0 :(得分:1)
如果您即时创建间隔表并将其与每个ProductionID的开始时间交叉连接,您可以从属于同一类别的MyTable中提取记录,并选择仅检索第一个。
; with timeSlots (startSlot, endSlot) as (
select 0, 10
union all
select 10, 20
union all
select 25, 30
union all
select 30, 40
union all
select 40, 60
union all
select 60, 120
union all
select 120, 180
),
startTimes (ProductionID, minTime) as (
select ProductionID, min([Time])
from MyTable
group by ProductionID
),
groupedTime (ProductionID, [Time], [Tmp], groupOrder) as (
select myTable.ProductionID,
myTable.Time,
myTable.Tmp,
row_number () over (partition by myTable.productionid, timeSlots.startSlot
order by mytable.Time) groupOrder
from startTimes
cross join timeslots
inner join myTable
on startTimes.ProductionID = myTable.ProductionID
and convert(varchar(8), dateadd(minute, timeSlots.startSlot, convert(datetime, startTimes.MinTime, 114)), 114) <= mytable.Time
and convert(varchar(8), dateadd(minute, timeSlots.endSlot, convert(datetime, startTimes.MinTime, 114)), 114) > myTable.Time
)
select ProductionID, [Time], [Tmp]
from groupedTime
where groupOrder = 1
答案 1 :(得分:0)
如果时间中没有丢失的序列,这将有效。我的意思是如果每增加10分钟有时间值,那么这将有效。
create table times([Time] time,tmp float,productionID int)
INSERT INTO times
VALUES('10:10:00',2.2,5),
('10:00:05',5.2,5),
('10:00:11',7.4,5),
('10:00:18',3.2,5),
('10:10:02',4.5,5),
('10:20:22',5.3,5)
select * from times
Declare @min_time time
select @min_time = MIN(time) from times
;WITH times1 as (select row_number() over (order by (select 0)) as id,time, tmp from times where productionID = 5)
,times2 as(
select id,time,tmp from times1 where time=@min_time
union all
select t1.id,t1.time,t1.tmp from times2 t2 inner join times1 t1 on cast(t1.time as varchar(5))=cast(DATEADD(mi,10,t2.Time) as varchar(5)) --where t1.id-1=t2.id
)
,result as (select MAX(time) as time from times2
group by CAST(time as varchar(5)))
select distinct t2.Time,t2.tmp from times2 t2,Result r where t2.Time =r.time order by 1