SELECT LEFT(CONVERT(VARCHAR(10), OutTime - InTime, 108), 5)
FROM Attendance
WHERE InTime BETWEEN '01-01-2016' AND '01-31-2016'
AND Employee=63
ORDER BY InTime
我已經得到了這個結果。如何在sql中獲取小時數和分鐘數
[
我要的是所有的時間的總和。我怎樣才能在Linq中編寫相同的查詢?
SELECT LEFT(CONVERT(VARCHAR(10), OutTime - InTime, 108), 5)
FROM Attendance
WHERE InTime BETWEEN '01-01-2016' AND '01-31-2016'
AND Employee=63
ORDER BY InTime
我已經得到了這個結果。如何在sql中獲取小時數和分鐘數
[
我要的是所有的時間的總和。我怎樣才能在Linq中編寫相同的查詢?
CREATE TABLE #Attendance(OutTime DateTime, InTime DateTime)
-- Sample Data
insert into #Attendance(InTime, outTime)
values ('2015-12-12 07:30', '2015-12-12 17:30'),
('2015-12-12 07:30', '2015-12-12 17:30'),
('2015-12-13 07:30', '2015-12-13 16:45'),
('2015-12-14 07:30', '2015-12-14 14:34'),
('2015-12-15 07:30', '2015-12-15 18:21')
-- Use DateDiff function to get total minutes between times to achieve greater accuracy then with 'hour'
-- Convert total minutes to hours after adding up total minutes
SELECT SUM(DATEDIFF(MINUTE, InTime , OutTime)) /60
FROM #Attendance
DROP TABLE #Attendance
更多的LINQ
現在:
public class Attendance
{
public DateTime InTime { get; set; }
public DateTime OutTime { get; set; }
}
[TestClass]
public class AttendanceUser
{
[TestMethod]
public void UseALambda()
{
var rand = new Random();
var attendances = Enumerable.Range(0, 10).Select(x =>
new Attendance { InTime = DateTime.Now.AddHours(-rand.Next(x)), OutTime = DateTime.Now.AddHours(rand.Next(x)) }).ToList();
var total = attendances.Sum(x => (x.OutTime - x.InTime).TotalMinutes)/60;
}
}
SQL Server不具有代表時間跨度一個 datetype。因此,它通常是最好的一切轉化爲int
s表示代表你需要的結果的粒度(這裏,分):
SELECT SUM(DATEDIFF(minute,InTime,OutTime)) as TotalMinutes
FROM Attendance
WHERE InTime BETWEEN '20160101' AND '20160131'
AND Employee=63
--ORDER BY InTime
而再轉化(天),小時和分鐘在表示層。
而且,指出的問題如下,如果你想包括在1月的最後一天發生事件,改變你的WHERE
條款:
SELECT SUM(DATEDIFF(minute,InTime,OutTime)) as TotalMinutes
FROM Attendance
WHERE InTime >= '20160101' AND InTime < '20160201'
AND Employee=63
附註:這是你有意忽略了什麼在一月的最後一天期間發生的*如果不是,那麼'WHERE InTime> ='20160101'和InTime <'20160201''會好得多。 –