我正在构建一个WCF
应用程序,用于计算进出时间之间的总时间,从数据库中获取数据我使用GROUP BY
子句按日期对数据进行分组,但我想要我的开始的日子&在早上6点结束,所以如果有人在早上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])
此外,如果有任何方法可以在存储过程中计算两次之间的差异,那么请提及它,它将是非常有用的。
答案 0 :(得分:0)
要在早上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])
答案 1 :(得分:0)
如何从Swipedatetime中扣除6个小时并按新值分组:
GROUP BY (Swipedatetime - INTERVAL '6 hours')
(这是postgresql,对于sql-server我认为你需要函数dateadd(小时,-6,Swipedatetime),或者沿着这条线的东西)
答案 2 :(得分:0)
您的解决方案只需要简单的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])