sql 暂时存储

go
if(object_id('groupbytest1') is not null) drop table groupbytest1;
go
create table groupbytest1( name varchar(10),score int default(0));
insert  into groupbytest1 (name,score)
 select 'aaa',11
 union select 'aaa',19
  union select 'bbb', 12
union select 'bbb',18
union select 'ccc',19
union select 'ddd', 21
go
select * from groupbytest1;
select  name ,sum(score) as totalscore from groupbytest1 group by name
select  name ,sum(score) as totalscore from groupbytest1 group by name having sum(score) ='30'
情景二:
 姓名 科目 分数
 张三 语文 30
张三 数学 50
张三 英语 70
李四 语文 50
李四 数学 80
李四 英语 90

期望查询结果:

 姓名 语文 数学 英语
 张三 30 50 70
李四 50 80 90
go
if(object_id('exam') is not null ) drop table exam;
go
create table exam(name varchar(10),ttype varchar(20) ,scroe int default(0));
insert into exam (name,ttype,scroe) select '张三','语文',30
union select '张三','数学',50
union select '张三','英语',70
union select '李四','语文',50
union select '李四','数学',80
union select '李四','英语',90
go
select * from exam;
go

select name as '姓名',
max(case ttype when '数学'  then  scroe  else 0 end) as '数学',
max(case ttype when '语文'  then scroe  else 0 end ) as '语文',
max(case ttype when '英语'  then scroe else 0 end ) as '英语'
from exam group by name
go
//查询以班级科目分组求平均分
select ttype as 科目,avg(scroe) as 平均分 from exam group by ttype
//查询以学生分组求学生的平均分
select  name as 姓名,avg(scroe) as  个人平均分 from exam group by name


SELECT * FROM ( SELECT DISTINCT name FROM exam
 )A
 OUTER APPLY(
 SELECT ttype= STUFF(REPLACE(
 REPLACE(
 (
 SELECT ttype FROM exam N
 WHERE name = A.name
 FOR XML AUTO
 ), '<N ttype="', '/ ')
 , '"/>', ''), 1, 1, '')
 )B
OUTER APPLY(
 SELECT scroe= stuff(
 REPLACE(
 REPLACE(
 (
 SELECT scroe FROM exam N
 WHERE name = A.name
 FOR XML AUTO
 ), '<N scroe="', '/ ')
 , '"/>', ''),1,1,'')
 
 )C
 
  REPLACE( (SELECT scroe FROM exam N  where name='张三'
 FOR XML AUTO),'<N scroe="',' /')

go
if(object_id('pagertest') is not null ) drop table pagertest
go
create table pagertest(id int primary key identity,flag int default(0),class varchar(10))
go
insert into pagertest (flag,class)
 select 1,11
 union all
 select 2,19
 union all
 select 3,12
 union all
 select 1,18
 union all
 select 2,19
 union all
 select 3,21
 union all
 select 1,11
 union all
 select 2,19
 union all
 select 3,12
 union all
 select 1,18
 union all
 select 2,19
 union all
 select 3,21
go
select * from pagertest
select top 4 * from pagertest where id not in (select top 6 id from pagertest order by id )
select top 4 * from pagertest where id >
(select  max(id) from (select top 6 id from pagertest order by id ) as a )

select distinct  class,
(select sum(id) from pagertest where pagertest.class=t.class )as flag1
from pagertest   t  group  by class

select * from pagertest where id = (select max(id) from pagertest)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值