1. 程式人生 > >sql 日周月統計和

sql 日周月統計和

sql 本日\本週\本月統計

SQL的本月統計和本週統計

本月統計(MySQL)
select * from booking where month(booking_time) = month(curdate()) and year(booking_time) = year(curdate())

本週統計(MySQL)
select * from spf_booking where month(booking_time) = month(curdate()) and week(booking_time) = week(curdate())

[SQLServer]
表名為:tableName
時間欄位名為:theDate

查詢本月的記錄
select * from tableName where DATEPART(mm, theDate) = DATEPART(mm, GETDATE()) and DATEPART(yy, theDate) = DATEPART(yy, GETDATE())

查詢本週的記錄
select * from tableName where DATEPART(wk, theDate) = DATEPART(wk, GETDATE()) and DATEPART(yy, theDate) = DATEPART(yy, GETDATE())

查詢本季的記錄
select * from tableName where DATEPART(qq, theDate) = DATEPART(qq, GETDATE()) and DATEPART(yy, theDate) = DATEPART(yy, GETDATE())

其中:GETDATE()是獲得系統時間的函式。

如: 
表:consume_record 
欄位:consume (money型別) 
date (datetime型別) 

請問怎麼寫四條sql語句分別按日,按周,按月,按季統計消費總量. 
如:1月 1200元 
2月 3400元 
3月 2800元 

--按日 
selectsum(consume),day([date]from consume_record whereyear([date]='2006'groupbyday([date]

--按周quarter 
selectsum(consume),datename(week,[date]from consume_record whereyear([date

]='2006'groupbydatename(week,[date]

--按月 
selectsum(consume),month([date]from consume_record whereyear([date]='2006'groupbymonth([date]

--按季 
selectsum(consume),datename(quarter,[date]from consume_record whereyear([date]='2006'groupbydatename(quarter,[date]

 

--指定日期你就看上面的例子變通下呀,無非就是一個聚合函式和Group by 


select[date],sum(consume) from consume_record where[date]between'2006-06-01'and'2006-07-10'groupby[date]

統計部落格聚合使用者點選次數
SELECT author, SUM(hits) AS hits
FROM infos
GROUP BY author
ORDER BY hits DESC

統計昨天的記錄
SELECT *
FROM infos
WHERE (DATEDIFF(d, pubdate, GETDATE()) = 1)

統計本週的記錄
SELECT *
FROM infos
WHERE (DATEPART(yy, pubdate) = DATEPART(yy, GETDATE())) AND (DATEPART(week,
      pubdate - 1) = DATEPART(week, GETDATE()))

統計本月的記錄:
SELECT *
FROM infos
WHERE (DATEPART(yy, pubdate) = DATEPART(yy, GETDATE())) AND (DATEPART([month],
      pubdate - 1) = DATEPART([month], GETDATE()))