【问题标题】:Group By query for date based on Custom Time Period根据自定义时间段分组查询日期
【发布时间】:2017-05-11 12:46:19
【问题描述】:

我正在构建一个WCF 应用程序,用于计算进出时间之间的总时间花费,以从数据库中获取数据我正在使用GROUP BY 子句按日期对数据进行分组,但我希望我的一天开始&早上 6:00 结束,所以如果有人在凌晨 3 点离开,它只会在当天添加。我正在使用以下命令查询

SELECT MIN([Swipedatetime]) AS [Entry]
     , MAX([Swipedatetime]) AS [Exit]
     , [UserID]
  FROM [Database_Name].[dbo].[Table_Name]
 where UserID = '100'
 GROUP 
    BY UserID
     , CAST (Swipedatetime as DATE)
 ORDER 
    BY MIN([Swipedatetime])

另外,如果有什么方法可以在存储过程中计算两次之间的差异,请提一下,这将很有用。

【问题讨论】:

  • 这毫无意义。如果您的“一天”从早上 6 点开始,那么凌晨 3 点的时间意味着该行被视为前一天,而不是“当前”天(这是在 Swipdatetime 列中找到的实际日期)。
  • @SMor 我想这就是我问我是否不自定义查询的原因,然后一天将从上午 12 点开始,仅在那个时间结束,我寻求帮助的原因是因为我想早上 6 点开始我的一天

标签: sql sql-server sql-server-2008 stored-procedures


【解决方案1】:

如何从 Swipedatetime 中减去 6 小时并按该新值分组:

GROUP BY (Swipedatetime - INTERVAL '6 hours')

(这是 postgresql,对于 sql-server,我认为您需要函数 dateadd(hour, -6, Swipedatetime) 或类似的东西)

【讨论】:

  • 它是dateadd(hour, -6, Swipedatetime),但在最坏的情况下,如果条目是在早上 6 点,那么在这种情况下,GROUP BY 子句可能会失败。对于所有其他情况,它会正常工作:)
【解决方案2】:

您的解决方案只需要简单的DATEADD 函数:

SELECT MIN([Swipedatetime]) AS [Entry]
     , MAX([Swipedatetime]) AS [Exit]
     , [UserID]
  FROM [dbo].[Table_Name]
 WHERE UserID = '100'
 GROUP 
    BY UserID
     , CAST (DATEADD(HOUR,6,Swipedatetime) AS DATE)
 ORDER 
    BY MIN([Swipedatetime])

【讨论】:

    【解决方案3】:

    要仅获取上午 6 点到下午 6 点之间的记录,您可以使用以下命令:

    where datepart(hour,[Swipedatetime]) > 6 
    and datepart(hour,[Swipedatetime]) <=18
    

    对于差异,您可以使用:

    select DATEDIFF(minute, MIN([Swipedatetime]), MAX([Swipedatetime]))
    

    那么完整的查询:

        declare @StartDate datetime = dateadd(HH, 6, convert(datetime, convert(date, getdate())))
        declare @EndDate datetime = dateadd(day,1,@Startdate)
    
    SELECT MIN([Swipedatetime]) AS [Entry]
         , MAX([Swipedatetime]) AS [Exit]
         , DATEDIFF(minute, MIN([Swipedatetime]), MAX([Swipedatetime])) AS[Diff]
         , [UserID]
      FROM [Database_Name].[dbo].[Table_Name]
     where UserID = '100'
    and [Swipedatetime] >= @Startdate
    and [Swipedatetime] < @EndDate
     GROUP 
        BY UserID
         , CAST (Swipedatetime as DATE)
     ORDER 
        BY MIN([Swipedatetime])
    

    【讨论】:

    • datepart(hour,[Swipedatetime])
    猜你喜欢
    • 1970-01-01
    • 2019-04-15
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多