统计每月

--这种形式只能查数据库存在的日期  比如数据库只有到六月分的 那六月以后的就没有
select 需要的字段,
  month (  日期字段) as 月份,
  sum( 要统计的字段) as 总数
from
  表
where
  year (  日期字段) = DATEPART(year, GETDATE())    -- 要查某年  这里获取当年
group by
 需要的字段,month (  日期字段)

----这种形式自定义月份  可查全年没有则为0
select  需要的字段,sum(case when  datepart(month,日期字段)=1 then 1 else 0 end) as '1月',
        sum(case when  datepart(month,日期字段)=2 then 1 else 0 end) as '2月',
        sum(case when  datepart(month,日期字段)=3 then 1 else 0 end) as '3月',
        sum(case when  datepart(month,日期字段)=4 then 1 else 0 end) as '4月',
        sum(case when  datepart(month,日期字段)=5 then 1 else 0 end) as '5月',
        sum(case when  datepart(month,日期字段)=6 then 1 else 0 end) as '6月',
        sum(case when  datepart(month,日期字段)=7 then 1 else 0 end) as '7月',
        sum(case when  datepart(month,日期字段)=8 then 1 else 0 end) as '8月',
        sum(case when  datepart(month,日期字段)=9 then 1 else 0 end) as '9月',
        sum(case when  datepart(month,日期字段)=10 then 1 else 0 end) as '10月',
        sum(case when  datepart(month,日期字段)=11 then 1 else 0 end) as '11月',
        sum(case when  datepart(month,日期字段)=12 then 1 else 0 end) as '12月'
    from 表 
    where year (  日期字段) = DATEPART(year, GETDATE())   group by 分组的字段-- 要查某年  这里获取当年
1、每年
select year(ordertime) 年,
sum(Total) 销售合计
from 订单表
group by year(ordertime)

2、每月
select year(ordertime) 年,
month(ordertime) 月,
sum(Total) 销售合计
from 订单表
group by year(ordertime),
month(ordertime

3、每日
select year(ordertime) 年,
month(ordertime) 月,
day(ordertime) 日,
sum(Total) 销售合计
from 订单表
group by year(ordertime),
month(ordertime),
day(ordertime)

另外每日也可以这样:
select convert(char(8),ordertime,112) dt,
sum(Total) 销售合计
from 订单表
group by convert(char(8),ordertime,112)

今天、昨天、本周、上周

--本周
select  * from 表  where   CONVERT(datetime, 时间字段, 101) >= DATEADD(week, DATEDIFF(week, 0, DATEADD(dd, - 1, GETDATE())), 0) AND CONVERT(datetime, 时间字段, 101) < DATEADD(week, DATEDIFF(week, 0, DATEADD(dd, - 1, GETDATE())), 7) --本周
--上周
select  * from 表  where   CONVERT(datetime, 时间字段, 101) >= DATEADD(week, - 1, DATEADD(week, DATEDIFF(week, 0, GETDATE()), 0)) AND CONVERT(datetime, 时间字段, 101)< DATEADD(week, - 1, DATEADD(week, DATEDIFF(week, 0, GETDATE()), 7))--上周
--今天
select  * from 表  where      CONVERT(datetime, 时间字段, 101), GETDATE()) = 0 AND YEAR(时间字段) = DATEPART(year, GETDATE())  
--昨天
  select  * from 表  where     DATEDIFF(day, CONVERT(datetime, 时间字段, 101), GETDATE()) = 1 

 

更多推荐

SQL语句统计每天、每月、每年、今天、昨天、本周、上周的数据