每天记录一点点
我希望有个如你一般的人
我希望有个如你一般的人,如山间清爽的风,如古城温暖的光,从清晨到夜晚,由山野到书房,一切问题的答案都很简单。我希望有个如你一般的人,贯彻未来,数遍生命的每个站点。
我们先分享一些经常用到的Sql语句
1,循环添加多条数据语句
--定义
declare @count int=1;
while @count<20
begin
--CAST:类型转换
insert into Users values('知青少年'+CAST(@count as nvarchar),'yh','2','文学社',null,null);
set @count=@count+1;
end
2,查询分页的sql语句
select * from (select ROW_NUMBER() over(order by id) as rowNumber,* from Users)
temp where rowNumber between 1 and 5;
-- 联表查询
selectu.UserName,p.Father,p.Mather fromUsersuleftjoinUser_Parentponu.Id=p.UserId;
三表查询
--join :显示查询左右的数据,只要有为空的就不查询显示
-- left join:显示左边所有的数据,如果右边没有与之匹配的就默认为空(要查询显示)
select u.UserName,p.Father,p.Mother,s.Sub,s.Score from Users u
leftjoin User_Parent p on u.Id=p.UserId
leftjoin User_Score s on u.Id=s.UserId;
-- 分组查询注意事项:用了groupby的sql语句,前面只能查分组的内容,查其他的话则报错
-- 解决方案:1,用运算方法让查询内容和分组内容一一对应,(如分组1例子)
-- 分组1
select Sub as '科目',SUM(Score)as '总分',max(Score)as '最高分',min(Score)as '最低分',avg(Score)as'平均分' from User_Score group by Sub
-- 分组查询加条件时:
Eg: 最高分:分数大于60
方法1:
select Sub as '科目',max(Score)as '最高分' from User_Score group by Sub having max(Score)>60
方法2:子查询作为一个临时变量表temp ,临时字段maxscore 进行查询(好处:不用带运算法则)
select* from
(select Sub as '科目',max(Score)as maxscore from User_Score group by sub)temp where maxscore>60
下面是Mvc EF 的后台代码
//三表联查的lamdba 语句 varquery=oae.Users.GroupJoin(oae.User_Parent, a=>a.Id, b=>b.UserId, (a, b) =>new { //把Id带着走 uid=a.Id, UserName=a.UserName, parents=b }).SelectMany(a=>a.parents.DefaultIfEmpty(), (a, b) =>new { uid=a.uid, UserName=a.UserName, Father=b.Father }).GroupJoin(oae.User_Score, a=>a.uid, b=>b.UserId, (a, b) =>new { //最后不用带Id UserName=a.UserName, Father=a.Father, score=b }).SelectMany(a=>a.score.DefaultIfEmpty(), (a, b) =>new { UserName=a.UserName, Father=a.Father, sub=b.Sub, Score=b.Score }); varresult=query.ToList(); ---------------------------------分组查询分数的条件语句------------------------------------------------------- linq varquery=from score in oae.User_Score group score by score.Sub into grouptemp select new { sub=grouptemp.Key, sum=grouptemp.Sum(a=>a.Score), max=grouptemp.Max(a=>a.Score), min=grouptemp.Min(a=>a.Score), avg=grouptemp.Average(a=>a.Score) }; //lamdba //AllScoreModel:返回的是json对象,要用集合接收,所以要ToList(); List<AllScoreModel>result2=oae.User_Score.GroupBy(a=>a.Sub).Select(grouptemp=>newAllScoreModel { sub=grouptemp.Key, sum=grouptemp.Sum(a=>a.Score), max=grouptemp.Max(a=>a.Score), min=grouptemp.Min(a=>a.Score), avg=grouptemp.Average(a=>a.Score) }).Where(a=>a.max>60).ToList(); //最高分大于60的
不用看啦,到底部啦,更多小知识请关注留言哦