


在SQL server數據存取過程中跳過非必要時間類型
添加時間:2014-3-24 17:22:28
添加:
思海網絡
也許發現其實在申報的程序數據報告時,大部分都是以天為單位的,有些可能是用小時為單位。但是通常采取的方式都是直接調用T-SQL的時間函數比如DataAdd和DataPart。
select UserId, SecondsSince/86400, count(*)
from Hits
group by UserId, SecondsSince/86400
--86400 is the number of seconds in a day
insert into HourlyHits (UserId, HoursSince, Count)
select UserId, SecondsSince/3600, count(*)
from Hits
group by UserId, SecondsSince/3600
--3600 is the number of seconds in a hour
public IList GetDailyHits(DateTime from, DateTime to)
{
command.CommandText = "select * from DailyHits where DaysSince > @From and DaysSince < @To";
command.Parameters.Add("@From", from.Substract(Epoch).TotalDays);
command.Parameters.Add("@To", to.Substract(Epoch).TotalDays);
...
}
這種方式并不能讓人滿意,這樣會向SQl Server中加載許多沒用的信息。數據庫中呈現的應該是我們真正需要的干凈而簡潔的信息。有什么辦法來處理這一問題嗎?
其實,可以借鑒Unix和PHP社區關于存取數據的處理方式。Unix的紀元是從1970年1月1日開始的。如果采取按秒計算的方式,在無符號的32位整數下,可以記錄136年。但是如果按分鐘計算,就是8100年。如果只是按天來計算那就差一點到12萬年了。
所以,最好參照算術的方式來控制這一問題。比如按天來統計每個人的信息。
insert into DailyHits (UserId, DaysSince, Count)select UserId, SecondsSince/86400, count(*)
from Hits
group by UserId, SecondsSince/86400
--86400 is the number of seconds in a day
insert into HourlyHits (UserId, HoursSince, Count)
select UserId, SecondsSince/3600, count(*)
from Hits
group by UserId, SecondsSince/3600
--3600 is the number of seconds in a hour
同樣適用于在C#下對于相對時間參數的控制。
public static readonly DateTime Epoch = new DateTime(1970, 1, 1);public IList GetDailyHits(DateTime from, DateTime to)
{
command.CommandText = "select * from DailyHits where DaysSince > @From and DaysSince < @To";
command.Parameters.Add("@From", from.Substract(Epoch).TotalDays);
command.Parameters.Add("@To", to.Substract(Epoch).TotalDays);
...
}
以上所舉的例子只是給出了簡化的代碼,但是所有重要的信息都已經包含在內了。這種方式不僅僅提供了很好的存儲工作方式,最重要的是其完全獨立于基礎數據庫。
關鍵字:數據庫、SQL server
新文章:
- CentOS7下圖形配置網絡的方法
- CentOS 7如何添加刪除用戶
- 如何解決centos7雙系統后丟失windows啟動項
- CentOS單網卡如何批量添加不同IP段
- CentOS下iconv命令的介紹
- Centos7 SSH密鑰登陸及密碼密鑰雙重驗證詳解
- CentOS 7.1添加刪除用戶的方法
- CentOS查找/掃描局域網打印機IP講解
- CentOS7使用hostapd實現無AP模式的詳解
- su命令不能切換root的解決方法
- 解決VMware下CentOS7網絡重啟出錯
- 解決Centos7雙系統后丟失windows啟動項
- CentOS下如何避免文件覆蓋
- CentOS7和CentOS6系統有什么不同呢
- Centos 6.6默認iptable規則詳解