【问题标题】:MSSQL Start and End Time Grouped by 10 Minute, for Elapsed TimeMSSQL 开始和结束时间按 10 分钟分组,表示经过的时间
【发布时间】:2022-01-17 14:34:11
【问题描述】:

我需要取一个已经汇总在一行中的开始和结束时间,并将其分成 10 分钟的窗口以及之间的总时间。

摘要行示例。

    StartDowntime   |    EndDowntime    | ElapsedSecs
    =================================================
    1/17/2022 8:00  |    1/17/2022 9:05 |   3900

期望的输出。

    Datetime        |    ElapsedSeconds  
    ===================================
    1/17/2022 8:00  |    600
    1/17/2022 8:10  |    600
    1/17/2022 8:20  |    600
    1/17/2022 8:30  |    600
    1/17/2022 8:40  |    600
    1/17/2022 8:50  |    600
    1/17/2022 9:00  |    300
    1/17/2022 9:10  |    0
    1/17/2022 9:20  |    0

我尝试过的。

     ;with cte as 
        (select MIN(StartDowntime) as MinDate
              , MAX(StartDowntime) as MaxDate
              , convert(varchar(14),StartDowntime, 120) as StartDate
              , DATEPART(minute, StartDowntime) /15 as GroupID
              , avg(ElapsedSecs) as AvgAmount
         from tblOKDryerDowntime
          where StartDowntime >= '1/1/2022 7:00' and EndDowntime <= '1/17/2022 8:00'
         group by convert(varchar(14),StartDowntime, 120)
             , DATEPART(minute, StartDowntime) /15
             , Dryer,DowntimeCode)
             
    select dateadd(minute, 15*GroupID, CONVERT(datetime,StartDate+'00'))
             as [Start Date]
           , AvgAmount as [Average Amount]
      from cte
      order by [Start Date] desc

这让我在最近的第 15 分钟开始时已经过去了。
但不会每 15 分钟停止一次。

【问题讨论】:

  • 请避免发布images 的数据,我们不能使用数据的图像,示例数据在您的问题中应该是consumable text,最好是create insert 语句,或者DB<>Fiddle。请参阅question guide
  • 到目前为止你有什么尝试?
  • 坚持从哪里开始,因为您必须生成一个有 10 分钟窗口的表格并加入它。无法概念化如何将开始和结束与仅摘要记录相关联
  • 您将从外连接数字/计数表开始。
  • 我编辑了原件。最好在手前有一张桌子,上面有 10 分钟的分段。

标签: sql sql-server database tsql


【解决方案1】:

发现递归 CTE 的魔力。

;WITH RCTE AS (
    SELECT 
      StartDowntime AS DownDatetime
    , 600 AS ElapsedSeconds
    , ElapsedSecs AS RemainingSeconds
    , EndDowntime
    , 1 AS Lvl
    FROM tblOKDryerDowntime
    
    UNION ALL
    
    SELECT
      DATEADD(second, ElapsedSeconds, DownDatetime)
    , iif(RemainingSeconds > ElapsedSeconds, 600, RemainingSeconds) 
    , iif(RemainingSeconds > ElapsedSeconds, RemainingSeconds - ElapsedSeconds, 0) 
    , EndDowntime
    , Lvl + 1
    FROM RCTE
    WHERE DownDatetime < EndDowntime
      AND RemainingSeconds > 0
)
SELECT DownDatetime, ElapsedSeconds
FROM RCTE
ORDER BY DownDatetime;
停机日期时间 |经过的秒数 :------------------------ | -------------: 2022-01-17 08:00:00.000 | 600 2022-01-17 08:10:00.000 | 600 2022-01-17 08:20:00.000 | 600 2022-01-17 08:30:00.000 | 600 2022-01-17 08:40:00.000 | 600 2022-01-17 08:50:00.000 | 600 2022-01-17 09:00:00.000 | 600 2022-01-17 09:10:00.000 | 300

dbfiddle here

上的演示

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多