你可以帮我吗,我使用下面的sql视图(然后我在水晶报告中使用)。我需要有日期差异(以分钟为单位),但现在我需要排除周末。 请帮助:)
SELECT intwc AS wc,
Datediff(n, start_date, end_date) AS time,
mh_start_date AS date,
'Repair' AS type
FROM dbo.xxxxxxx
答案 0 :(得分:5)
这是@ bendataclear答案的修改版本。它直接计算周末分钟,而不是计算天数并乘以24 * 60。它还占星期六/星期日开始/结束的所有4种组合
我正在使用CONVERT(date,@StartDate)
获取@StartDate
的日期,时间为00:00:00
,然后用于计算部分星期日和星期六。有better ways这样做,但我选择了最简单的。
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2013/03/15 23:30:00'
SET @EndDate = '2013/03/17 00:30:00'
SELECT
( DATEDIFF(MINUTE, @StartDate, @EndDate)
- ( DATEDIFF(wk, @StartDate,@EndDate)*(2*24*60)
-- End on Sunday
-(CASE WHEN DATEPART(dw, @EndDate) = 1 THEN 24.0*60-DATEDIFF(minute,CONVERT(date,@EndDate),@EndDate) ELSE 0 END)
-- Start on Saturday
-(CASE WHEN DATEPART(dw, @StartDate) = 7 THEN DATEDIFF(minute,CONVERT(date,@StartDate),@StartDate) ELSE 0 END)
-- End on Saturday
+(CASE WHEN DATEPART(dw, @EndDate) = 7 THEN DATEDIFF(minute,CONVERT(date,@EndDate),@EndDate) ELSE 0 END)
-- Start on Saturday
+(CASE WHEN DATEPART(dw, @StartDate) = 1 THEN 24.0*60-DATEDIFF(minute,CONVERT(date,@StartDate),@StartDate) ELSE 0 END)
)
)
答案 1 :(得分:1)
此答案假设您希望在一分钟内排除周末,同时它完全基于this question中的答案:
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2013/03/15 23:30:00'
SET @EndDate = '2013/03/18 00:30:00'
SELECT
(DATEDIFF(MINUTE, @StartDate, @EndDate))
-(DATEDIFF(wk, @StartDate, @EndDate) * (2*24*60))
-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN (24*60) ELSE 0 END)
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN (24*60) ELSE 0 END)
答案 2 :(得分:0)
SELECT intwc AS wc,
Datediff(n, start_date, end_date) AS time,
mh_start_date AS date,
'Repair' AS type
FROM dbo.xxxxxxx
Where DATEPART(dw, start_date) NOT IN (1, 7) and DATEPART(dw, end_date) NOT IN (1, 7)
答案 3 :(得分:0)
因此,您需要能够处理一些CASE语句来处理所有边缘情况。这是我放在一起的一个例子。 Numbers表只是一个计数表,在本例中为1到30。
CREATE TABLE #times (id INT IDENTITY(1,1), start_stamp DATETIME, end_stamp DATETIME)
INSERT INTO #times
(
start_stamp ,
end_stamp
)
SELECT DATEADD(DAY, -2*Number, CURRENT_TIMESTAMP), DATEADD(DAY, -1*Number, CURRENT_TIMESTAMP)
FROM Common.NUMBERS
WHERE Number < 31
SELECT id, start_stamp, end_stamp,
CASE WHEN DATEDIFF(DAY, start_stamp, end_stamp) < 7 THEN
CASE WHEN DATEPART(weekday, start_stamp) < DATEPART(weekday, end_stamp)
THEN DATEDIFF(MINUTE, start_stamp, DATEADD(HOUR, -48, end_stamp))
ELSE DATEDIFF(MINUTE, start_stamp, end_stamp) END
ELSE DATEDIFF(MINUTE, start_stamp, DATEADD(HOUR, -48*(DATEDIFF(WEEK, start_stamp, end_stamp)), end_stamp)) END
+ CASE WHEN DATENAME(weekday,start_stamp) IN ('Sunday', 'Saturday') THEN 1440 ELSE 0 END
+ CASE WHEN DATENAME(weekday,end_stamp) IN ('Sunday', 'Saturday') THEN 1440 ELSE 0 END
FROM #times
可能有更优雅的方法,但代码允许您针对整个结果集运行并按行计算。