问题
Say, I have the following SQL Server 2008 table with data:
CREATE TABLE tbl (dtIn DATETIME2, dtOut DATETIME2)
INSERT tbl VALUES
('9/10/2012 5:14:10 AM', '9/10/2012 5:15:09 AM'),
('9/10/2012 5:16:12 AM', '9/10/2012 5:18:12 AM'),
('9/10/2012 5:18:43 AM', '9/10/2012 5:23:04 AM'),
('9/10/2012 5:25:17 AM', '9/10/2012 5:26:05 AM'),
('9/10/2012 5:26:57 AM', '9/10/2012 5:29:19 AM'),
('9/10/2012 5:31:41 AM', '9/10/2012 5:32:41 AM'),
('9/10/2012 5:33:16 AM', '9/10/2012 5:34:08 AM'),
('9/10/2012 5:35:25 AM', '9/10/2012 5:49:46 AM'),
('9/10/2012 5:55:35 AM', '9/10/2012 5:56:48 AM'),
('9/10/2012 5:58:54 AM', '9/10/2012 5:59:59 AM')
and then I ran this query:
WITH ctx AS(
SELECT datediff(minute, dtIn, dtOut) AS d FROM tbl
)
SELECT SUM(d) FROM ctx
I get 30 minutes.
But when I try the same with C#:
double fM = 0;
fM += (DateTime.Parse("9/10/2012 5:15:09 AM") - DateTime.Parse("9/10/2012 5:14:10 AM")).TotalMinutes;
fM += (DateTime.Parse("9/10/2012 5:18:12 AM") - DateTime.Parse("9/10/2012 5:16:12 AM")).TotalMinutes;
fM += (DateTime.Parse("9/10/2012 5:23:04 AM") - DateTime.Parse("9/10/2012 5:18:43 AM")).TotalMinutes;
fM += (DateTime.Parse("9/10/2012 5:26:05 AM") - DateTime.Parse("9/10/2012 5:25:17 AM")).TotalMinutes;
fM += (DateTime.Parse("9/10/2012 5:29:19 AM") - DateTime.Parse("9/10/2012 5:26:57 AM")).TotalMinutes;
fM += (DateTime.Parse("9/10/2012 5:32:41 AM") - DateTime.Parse("9/10/2012 5:31:41 AM")).TotalMinutes;
fM += (DateTime.Parse("9/10/2012 5:34:08 AM") - DateTime.Parse("9/10/2012 5:33:16 AM")).TotalMinutes;
fM += (DateTime.Parse("9/10/2012 5:49:46 AM") - DateTime.Parse("9/10/2012 5:35:25 AM")).TotalMinutes;
fM += (DateTime.Parse("9/10/2012 5:56:48 AM") - DateTime.Parse("9/10/2012 5:55:35 AM")).TotalMinutes;
fM += (DateTime.Parse("9/10/2012 5:59:59 AM") - DateTime.Parse("9/10/2012 5:58:54 AM")).TotalMinutes;
I get fM = 29.016666666666669.
By adding Math.Round() to each C# statement, I get 28.0. By adding Math.Floor() I get 25.0. By adding Math.Ceiling I get 33.0.
Can someone explain this discrepancy?
回答1:
The return value of each is measuring different things.
It would be prudent to pay attention to the DATEDIFF docs here:
Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate.
which leads to the following 2 second interval:
SELECT datediff(minute, '9/10/2012 5:14:59 AM', '9/10/2012 5:15:01 AM')
returning 1 because it crosses a minute boundary. I suspect that you did not take this behaviour into account.
来源:https://stackoverflow.com/questions/12657680/datediff-with-minute-does-not-return-expected-value