日期:2014-05-17  浏览次数:20476 次

新年好,请教with rollup grouping的用法???
1.表:
 create table #test(dept varchar(20),name varchar(20),country varchar(20),play varchar(20),age int,score int)
 insert into #test select '技术部','张一','中国','足球',28,120
  insert into #test select '技术部','李一','中国','篮球',28,120
   insert into #test select '生产部','张二','中国','足球',28,120
  insert into #test select '生产部','李二','英国','羽毛球',28,120
2.请问按照dept进行分组小计,最后合计,要求要显示所有字段,在dept列显示小计、合计,用with rollup 是怎样进行编写的啊?
3.select 时,想增加一个字段,根据记录从1自动递增起,用什么语句呢?

------解决方案--------------------
select case when grouping(dept) =1 then '合计' else dept end ,
       case when grouping(country)=1 then case when grouping(dept) =0 then '小计' else '' end else country end,
avg(age),avg(score)
from #test
group by dept,country
with rollup

至于增加自增列,2005及以上版本直接用排名函数就行