SqlServer 數據庫按日期分組查詢。


要求    兩個時間點:一個開始時間(2007/09/08 09:10:43),一個結束時間(2007/10/09 04:32:37)
              數據庫中表的字段有 id(編號)  name(名字)   time(註冊時間) 表名爲table
                        需要查詢比如在兩個時間段內 比如如上面時間點 
                    求:1.9月,10月分別有多少個id?
                                   2.兩個時間段的單個日中分別有多少個id?
                                   3兩個時間段的單個小時中分別有多少個id?
  我的思路是分別按 月,日,小時分組,然後統計?  select count(id) from table where time>='2007/09/08 09:10:43' and time<=
'2007/10/09 04:32:37' 
     但我做出來的都只能按秒分組,請各位高人指點 怎麼才能實現 按月或者按日,按小時分組?先謝謝啦!!



--按照月份統計
select count(id) cnt,datepart(mm,time) [Month]
from [table]
where [time] between '2007/09/08 09:10:43' and '2007/10/09 04:32:37'
group by datepart(mm,time)
--按照日統計
select count(id) cnt,datepart(dd,time) [Day]
from [table]
where time between '2007/09/08 09:10:43' and '2007/10/09 04:32:37'
group by datepart(dd,time)
--按照小時統計
select count(id) cnt,datepart(hh,time) [Hour]
from [table]
where [time] between '2007/09/08 09:10:43' and '2007/10/09 04:32:37'
group by datepart(hh,time)

轉自 http://www.itpub.net/thread-917632-1-1.html



版主

卡卡西

精華貼數
0
專家積分
0
技術積分
4377
社區積分
0
註冊時間
2007-3-10
論壇徽章:
22
'會員2007貢獻徽章'2012新春紀念徽章'2012新春紀念徽章'2012新春紀念徽章'2012新春紀念徽章'馬上有車'馬上有房'馬上有錢'馬上有對象'2012新春紀念徽章'管理團隊成員'2011新春紀念徽章
2#
 發表於 2007-12-27 16:23:45 |只看該作者
--按照月份統計
select count(id) cnt,datepart(mm,time) [Month]
from [table]
where [time] between '2007/09/08 09:10:43' and '2007/10/09 04:32:37'
group by datepart(mm,time)
--按照日統計
select count(id) cnt,datepart(dd,time) [Day]
from [table]
where time between '2007/09/08 09:10:43' and '2007/10/09 04:32:37'
group by datepart(dd,time)
--按照小時統計
select count(id) cnt,datepart(hh,time) [Hour]
from [table]
where [time] between '2007/09/08 09:10:43' and '2007/10/09 04:32:37'
group by datepart(hh,time)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章