比如 表 table1,分类 type,读取分类前5条,合并在联查,并且排序
select from
(
SELECT top 5 FROM table1 where type=1
UNION
SELECT top 5 FROM table1 where type=2
UNION
SELECT top 5 FROM table1 where type=3
) as table_new order by id desc
select from stu_score order by 语文 desc, 数学;
ORDER BY子句用于根据一个或多个列以升序或降序对数据进行排序。 默认情况下,一些数据库排序查询结果按升序排列。
语法:
SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, columnN] [ASC | DESC];
可以在ORDER BY子句中使用多个列。 确保您使用的任何列进行排序,该列应该在列表中。
扩展资料:
常用的 T-SQL 语言:
1、分组:
group by在order by 前面。
select cname from first group by cname;
按照姓名对表格分组。
2、having 子句对分组结果再选择:
select cname from first group by cname having cname like '张%'
3、转换数据类型函数:
convert(a,b):强制类型转换
a 是要转换的数据类型,b 是被转换的数据类型
declare @number intset @number = 3 select convert(char(1),@number) as 转换后
4、聚合函数
avg,max,sum,count()
select count() as 行数,avg(convert(int,cage)) as 平均年龄,max(cbirthday) as 最晚出生年月,sum(cid) as id的和 from first
只能用存储过程
思路如下
将分组那个字段比如是A
Create temp table tmp_b
foreach
select distinct A into bianlianga from table
insert into tmp_b
select top 2 B from table where A=bianlianga order by B ;
delete from table where A=bianlianga and B in(select from tmp_b);
end foreach
单表 *** 作的主要使用语句为SELECT语句,在SELECT语句中,可以根据自己对数据的需求,使用不同的查询条件。
数据库(Database),简而言之可视为电子化的文件柜——存储电子文件的处所,用户可以对文件中的数据运行新增、截取、更新、删除等 *** 作。
所谓“数据库”系以一定方式储存在一起、能予多个用户共享、具有尽可能小的冗余度、与应用程序彼此独立的数据集合。一个数据库由多个表空间(Tablespace)构成。
SQL取分组中的前几名
[sql] >
with tmp as
(select row_number() over(order by count(val)) as rn,val,count(val) as cnum from table1 group by val)
select from tmp where rn<3
要想区别并列现象还要复杂一些,可能简单的语句解决不了
select
分组,
人物,
RANK()
OVER
(partition
BY
分组
ORDER
BY
人物)
from
你的表
这个语句就可以满足你的分组排序需求,最后一列的结果为你需要的排序序号
以上就是关于sql 查询每个分组下的前几条记录并排序全部的内容,包括:sql 查询每个分组下的前几条记录并排序、对students数据库的表stu_score查询所以记录,结果按照语文成绩降序,数学成绩升序进行排列。、sql语句,先分组查询,在算每组的行数,在排序等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)