数据库
首页 > 数据库> > SQL语句统计每天、每月、每年的数据

SQL语句统计每天、每月、每年的数据

作者:互联网

统计每月

--这种形式只能查数据库存在的日期  比如数据库只有到六月分的 那六月以后的就没有
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)

 

一只小程序员 发布了122 篇原创文章 · 获赞 9 · 访问量 7万+ 私信 关注

标签:语句,case,ordertime,datepart,每月,sum,when,month,SQL
来源: https://blog.csdn.net/qq_39569480/article/details/104529938