如何按月分组统计
我有一表tbdata ,字段有
TLname (nvarchar),TLdate (datetime),TLsum(decimal)分别为名称,写入时间 和数量
一年后运行下来,现在要根据tlname 来分组汇总tlsum ,并且要求按月份进行统计,从一月到12月。如何写呢?
[解决办法]
select TLname,MONTH(TLdate) as TLmonth,SUM(TLsum) TLsum
from tbdata
group by TLname,MONTH(TLdate)
[解决办法]
Create table tbdata (TLname nvarchar(8),TLdate datetime,TLsum decimal)
Insert tbdata
select '第一名','2012-01-01',100 union all
select '第一名','2012-02-01',600 union all
select '第二名','2012-03-01',500 union all
select '第二名','2012-03-01',400 union all
select '第三名','2012-04-01',200 union all
select '第四名','2012-05-01',300
select TLname,sum(TLsum) as 数量,month(TLdate) as 月份 from tbdata group by TLname,month(TLdate) order by TLname
TLname 数量 月份
-------- ------------ -----------
第一名 100 1
第一名 600 2
第三名 200 4
第二名 900 3
第四名 300 5
(5 行受影响)
[解决办法]
Create table tbdata (TLname nvarchar(8),TLdate datetime,TLsum decimal)
Insert tbdata
select '张三','2012-01-01',100 union all
select '李四','2012-02-01',600 union all
select '张三','2012-03-01',500 union all
select '李四','2012-03-01',400 union all
select '李四','2012-04-01',200 union all
select '张三','2012-05-01',300 union all
select '张三','2013-01-01',100 union all
select '李四','2013-02-01',200 union all
select '张三','2013-03-01',200 union all
select '李四','2013-03-01',700 union all
select '李四','2013-04-01',900 union all
select '张三','2013-05-01',300
select year(tldate) as 年份,TLname
,[1]=sum(case when month(tldate)=1 then tlsum else 0 end)
,[2]=sum(case when month(tldate)=2 then tlsum else 0 end)
,[3]=sum(case when month(tldate)=3 then tlsum else 0 end)
,[4]=sum(case when month(tldate)=4 then tlsum else 0 end)
,[5]=sum(case when month(tldate)=5 then tlsum else 0 end)
,[6]=sum(case when month(tldate)=6 then tlsum else 0 end)
,[7]=sum(case when month(tldate)=7 then tlsum else 0 end)
,[8]=sum(case when month(tldate)=8 then tlsum else 0 end)
,[9]=sum(case when month(tldate)=9 then tlsum else 0 end)
,[10]=sum(case when month(tldate)=10 then tlsum else 0 end)
,[11]=sum(case when month(tldate)=11 then tlsum else 0 end)
,[12]=sum(case when month(tldate)=12 then tlsum else 0 end)
from tbdata
group by year(tldate),TLname

[解决办法]
create table #tbdata
(
tlname nvarchar(50),
tldate datetime,
tlsum decimal(18,2)
)
insert into #tbdata(tlname,tldate,tlsum)
select '张三','2012-06-02','8' union all
select '张三','2012-09-01','10' union all
select '李四','2012-08-01','9' union all
select '王五','2012-08-01','8' union all
select '张三','2012-07-01','6' union all
select '张三','2012-06-01','5' union all
select '李四','2012-06-01','5'
select tlname,tldate,tlsum from #tbdata
declare @i int
set @i=1
while @i<=12
begin
select @i as 月份,tlname,sum(tlsum) as tlsum from #tbdata where @i=month(tldate) group by tlname
set @i=@i+1
end
drop table #tbdata