想知道是否有人可以帮助我。我有一个包含以下字段的简单表格。
ID(int), TimeStamp(DateTime), 状态(NvarChar)
我需要在10分钟的插槽中生成一个包含所有状态计数的表格,如同提供的示例一样。我们的想法是在仪表板中生成Google Line Chart,每10分钟刷新一次。
实施例: Table
任何帮助将不胜感激。
何
答案 0 :(得分:0)
你可以使用递归cte创建你的时间段并加入它。
with cte as (
select DATETIMEFROMPARTS(datepart(year,getdate()), datepart(month,getdate()), datepart(day,getdate()), datepart(hour, getdate()), floor((datepart(minute, getdate()) - 9) / 10) * 10, 0, 0) as startDT,
DATETIMEFROMPARTS(datepart(year,getdate()), datepart(month,getdate()), datepart(day,getdate()), datepart(hour, getdate()), floor((datepart(minute, getdate()) + 9) / 10) * 10, 0, 0) as endDT
union all
select DATEADD(minute, -10, startDT),
DATEADD(minute, -10, endDt)
from cte
where DATEADD(minute, -130, getdate()) < DATEADD(minute, -10, startDT)
)
select endDt as [Period],
count(case when [Status] = 'OK' then 1 end) as Status_OK,
count(case when [Status] <> 'OK' then 1 end) as Status_NOK
from cte
left join myTable on [TimeStamp] >= startDT and [TimeStamp] < endDT
group by endDT
如果您更喜欢使用dateadd,那么
;with cte as (
select dateadd(minute, datediff(minute, 0, getdate()) / 10 * 10, 0) as startDT,
dateadd(minute, datediff(minute, 0, getdate()) / 10 * 10 + 10, 0) as endDT
union all
select dateadd(minute, -10, startDT),
dateadd(minute, -10, endDt)
from cte
where dateadd(minute, -130, getdate()) < dateadd(minute, -10, startDT)
)
select endDt as [Period],
count(case when [Status] = 'OK' then 1 end) as Status_OK,
count(case when [Status] <> 'OK' then 1 end) as Status_NOK
from cte
left join myTable on [TimeStamp] >= startDT and [TimeStamp] < endDT
group by endDT