110,539
社区成员
发帖
与我相关
我的任务
分享
create table tb
(
编号 int,
车号 nvarchar(50),
货名 nvarchar(50),
净重 int,
计量时间 datetime
)
insert into tb(编号, 车号, 货名, 净重, 计量时间)
select '01','A01', '货物A', 1000, '2011-1-20 11:14:01'
union all
select '01','A01', '货物A', 1000, '2011-1-23 11:14:01'
union all
select '02','A02', '货物B', 4000, '2011-2-20 11:14:01'
union all
select '03','A03', '货物C', 3000, '2011-3-20 11:14:01'
union all
select '04','A04', '货物D', 1000, '2011-4-20 11:14:01'
select 货名,
[1月份]=(case when month(计量时间)=1 then 净重 else 0 end),
[2月份]=(case when month(计量时间)=2 then 净重 else 0 end),
[3月份]=(case when month(计量时间)=3 then 净重 else 0 end),
[4月份]=(case when month(计量时间)=4 then 净重 else 0 end),
[5月份]=(case when month(计量时间)=5 then 净重 else 0 end),
[6月份]=(case when month(计量时间)=6 then 净重 else 0 end),
[7月份]=(case when month(计量时间)=7 then 净重 else 0 end),
[8月份]=(case when month(计量时间)=8 then 净重 else 0 end),
[9月份]=(case when month(计量时间)=9 then 净重 else 0 end),
[10月份]=(case when month(计量时间)=10 then 净重 else 0 end),
[11月份]=(case when month(计量时间)=11 then 净重 else 0 end),
[12月份]=(case when month(计量时间)=12 then 净重 else 0 end)
into #tb
from tb
select 货名,
sum([1月份]) as [1月份],
车数=(select count(1) from #tb where 货名=t.货名 and [1月份]!=0),
sum([2月份]) as [2月份],
车数=(select count(1) from #tb where 货名=t.货名 and [2月份]!=0),
sum([3月份]) as [3月份],
车数=(select count(1) from #tb where 货名=t.货名 and [3月份]!=0),
sum([4月份]) as [4月份],
车数=(select count(1) from #tb where 货名=t.货名 and [4月份]!=0),
sum([5月份]) as [5月份],
车数=(select count(1) from #tb where 货名=t.货名 and [5月份]!=0),
sum([6月份]) as [6月份],
车数=(select count(1) from #tb where 货名=t.货名 and [6月份]!=0),
sum([7月份]) as [7月份],
车数=(select count(1) from #tb where 货名=t.货名 and [7月份]!=0),
sum([8月份]) as [8月份],
车数=(select count(1) from #tb where 货名=t.货名 and [8月份]!=0),
sum([9月份]) as [9月份],
车数=(select count(1) from #tb where 货名=t.货名 and [9月份]!=0),
sum([10月份]) as [10月份],
车数=(select count(1) from #tb where 货名=t.货名 and [10月份]!=0),
sum([11月份]) as [11月份],
车数=(select count(1) from #tb where 货名=t.货名 and [11月份]!=0),
sum([12月份]) as [12月份],
车数=(select count(1) from #tb where 货名=t.货名 and [12月份]!=0)
from #tb t group by 货名
drop table #tb
select 货名,
[1月份]=(case when month(计量时间)=1 then 净重 else 0 end),
[2月份]=(case when month(计量时间)=2 then 净重 else 0 end),
[3月份]=(case when month(计量时间)=3 then 净重 else 0 end),
[4月份]=(case when month(计量时间)=4 then 净重 else 0 end),
[5月份]=(case when month(计量时间)=5 then 净重 else 0 end),
[6月份]=(case when month(计量时间)=6 then 净重 else 0 end),
[7月份]=(case when month(计量时间)=7 then 净重 else 0 end),
[8月份]=(case when month(计量时间)=8 then 净重 else 0 end),
[9月份]=(case when month(计量时间)=9 then 净重 else 0 end),
[10月份]=(case when month(计量时间)=10 then 净重 else 0 end),
[11月份]=(case when month(计量时间)=11 then 净重 else 0 end),
[12月份]=(case when month(计量时间)=12 then 净重 else 0 end)
from tb