数据库:MSSQL
表:
区域 年 月 金额
北京 2005 5 1000
上海 2005 2 2000
北京 2005 3 3000
上海 2005 1 4000
北京 2004 4 3000
北京 2005 5 1000
上海 2005 2 2000
北京 2005 3 3000
上海 2005 1 4000
北京 2004 4 3000
要求结果:
区域 年 月 金额
北京 2004 4 3000
2005 3 3000
5 1000
上海 2005 1 4000
2 2000
北京 2004 4 3000
2005 3 3000
5 1000
上海 2005 1 4000
2 2000
---------------------------
create table #t(区域 varchar(10), 年 char(4), 月 char(2), 金额 float)
go
insert into #t values('北京', 2005, 5, 1000)
insert into #t values('上海', 2005, 2, 2000)
insert into #t values('北京', 2005, 3, 3000)
insert into #t values('上海', 2005, 1, 4000)
insert into #t values('北京', 2004, 4, 3000)
go
go
insert into #t values('北京', 2005, 5, 1000)
insert into #t values('上海', 2005, 2, 2000)
insert into #t values('北京', 2005, 3, 3000)
insert into #t values('上海', 2005, 1, 4000)
insert into #t values('北京', 2004, 4, 3000)
go
select identity(int,1,1) as id,* into #tt
from #t
order by 区域,年,月
from #t
order by 区域,年,月
select id,
(case when id=(select top 1 id from #tt where 区域=t.区域 order by 区域) then 区域 else '' end) as 区域,
(case when id=(select top 1 id from #tt where 年=t.年 order by 年) then 年 else '' end) as 年,
月,金额
from #tt t
(case when id=(select top 1 id from #tt where 区域=t.区域 order by 区域) then 区域 else '' end) as 区域,
(case when id=(select top 1 id from #tt where 年=t.年 order by 年) then 年 else '' end) as 年,
月,金额
from #tt t
order by 区域+年+月
注:仍然需要一个唯一id值来区分,才好做。否则,只能:
select
(case when (区域=(select top 1 区域 from #t where 区域=t.区域 order by 区域,年,月) and 年=(select top 1 年 from #t where 区域=t.区域 order by 区域,年,月) and 月=(select top 1 月 from #t where 区域=t.区域 order by 区域,年,月)) then 区域 else '' end) as 区域,
(case when (区域=(select top 1 区域 from #t where 区域=t.区域 order by 区域,年,月) and 年=(select top 1 年 from #t where 区域=t.区域 order by 区域,年,月) and 月=(select top 1 月 from #t where 区域=t.区域 order by 区域,年,月)) then 年 else '' end) as 年,
月,金额
from #t t
order by 区域+年+月
(case when (区域=(select top 1 区域 from #t where 区域=t.区域 order by 区域,年,月) and 年=(select top 1 年 from #t where 区域=t.区域 order by 区域,年,月) and 月=(select top 1 月 from #t where 区域=t.区域 order by 区域,年,月)) then 区域 else '' end) as 区域,
(case when (区域=(select top 1 区域 from #t where 区域=t.区域 order by 区域,年,月) and 年=(select top 1 年 from #t where 区域=t.区域 order by 区域,年,月) and 月=(select top 1 月 from #t where 区域=t.区域 order by 区域,年,月)) then 年 else '' end) as 年,
月,金额
from #t t
order by 区域+年+月