select
单位名,
第一季度数量=sum(case 季度 when 1 then 数量 else 0 end),
第二季度数量=sum(case 季度 when 2 then 数量 else 0 end),
第三季度数量=sum(case 季度 when 3 then 数量 else 0 end),
第四季度数量=sum(case 季度 when 4 then 数量 else 0 end),
年度
into #T
from
表
group by
单位名,年度
order by
单位名,年度select * from #T
单位名,
第一季度数量=sum(case 季度 when 1 then 数量 else 0 end),
第二季度数量=sum(case 季度 when 2 then 数量 else 0 end),
第三季度数量=sum(case 季度 when 3 then 数量 else 0 end),
第四季度数量=sum(case 季度 when 4 then 数量 else 0 end),
年度
into #T
from
表
group by
单位名,年度
order by
单位名,年度select * from #T
select 单位名 as 单位,
第一季度数量=isnull(sum(case when 季度=1 then 数量 else 0 end ),0),
第二季度数量=isnull(sum(case when 季度=2 then 数量 else 0 end ),0),
第三季度数量=isnull(sum(case when 季度=3 then 数量 else 0 end ),0),
第四季度数量=isnull(sum(case when 季度=4 then 数量 else 0 end ),0),
年度
from tablename
group by 单位名,年度
select * from #tdrop table #t
select 单位名 as 单位,
第一季度数量=isnull(sum(case when 季度=1 then 数量 else 0 end ),0),
第二季度数量=isnull(sum(case when 季度=2 then 数量 else 0 end ),0),
第三季度数量=isnull(sum(case when 季度=3 then 数量 else 0 end ),0),
第四季度数量=isnull(sum(case when 季度=4 then 数量 else 0 end ),0),
年度
from tablename
group by 单位名,年度
order by 单位名,年度
select * from #tdrop table #t
是这样
a 2 0 0 0
b 0 1 0 0我写了个测试环境 大家可以去试试
create table t1
(jd int,
dw char,
qwt int,
y int)
go
insert t1
select 1,'a',2,2005 union all
select 1,'a',3,2005 union all
select 2,'b',1,2005
go
(jd int,
dw char,
qwt int,
y int)
go
insert t1
select 1,'a',2,2005 union all
select 1,'a',3,2005 union all
select 2,'b',1,2005
goselect
单位 = dw,
第一季度数量=isnull(sum(case when jd=1 then qwt else 0 end ),0),
第二季度数量=isnull(sum(case when jd=2 then qwt else 0 end ),0),
第三季度数量=isnull(sum(case when jd=3 then qwt else 0 end ),0),
第四季度数量=isnull(sum(case when jd=4 then qwt else 0 end ),0),
年度 = y
into #t from t1 group by dw,y
select * from #t
/*
a 5 0 0 0 2005
b 0 1 0 0 2005
*/drop table #t,t1
(jd int,
dw char,
qwt int,
y int)
go
insert t1
select 1,'a',2,2005 union all
select 1,'a',3,2005 union all
select 2,'b',1,2005
goselect
dw as单位,
第一季度数量=isnull(sum(case when jd=1 then qwt else 0 end ),0),
第二季度数量=isnull(sum(case when jd=2 then qwt else 0 end ),0),
第三季度数量=isnull(sum(case when jd=3 then qwt else 0 end ),0),
第四季度数量=isnull(sum(case when jd=4 then qwt else 0 end ),0),
y as 年度
into #t from t1 group by dw,y
select * from #t
/*
a 5 0 0 0 2005
b 0 1 0 0 2005
*/drop table #t,t1