34,590
社区成员
发帖
与我相关
我的任务
分享
select *
from
(select *,COUNT(学号) over (partition by 班级) as 人数 from table_XXX) as A
order by 人数 desc,班级,学号
USE tempdb
GO
IF OBJECT_ID('t') IS NOT NULL
DROP TABLE t
GO
CREATE TABLE t(
sno VARCHAR(10),
cname NVARCHAR(20)
)
GO
INSERT INTO t(sno,cname)
select '1001','大数据1班'
union all select '1002','Java1班'
union all select '1003','Java1班'
union all select '1004','Java1班'
union all select '1005','Java1班'
union all select '1006','Java1班'
union all select '1007','Java1班'
union all select '1008','Python1班'
union all select '1009','Python1班'
union all select '1010','Python1班'
union all select '1011','Python1班'
union all select '1012','Python1班'
union all select '1013','Python1班'
union all select '1014','Python1班'
union all select '1015','Python1班'
union all select '1016','Python1班'
union all select '1017','Python2班'
union all select '1022','Python2班'
union all select '1023','Python2班'
union all select '1024','Python2班'
union all select '1025','Python2班'
;WITH cte AS (
SELECT cname,COUNT(1) AS cnt FROM t GROUP BY cname
)
SELECT t.* FROM cte INNER JOIN t ON cte.cname=t.cname
ORDER BY cte.cnt DESC;
/*
sno cname
---------- --------------------
1008 Python1班
1009 Python1班
1010 Python1班
1011 Python1班
1012 Python1班
1013 Python1班
1014 Python1班
1015 Python1班
1016 Python1班
1002 Java1班
1003 Java1班
1004 Java1班
1005 Java1班
1006 Java1班
1007 Java1班
1017 Python2班
1022 Python2班
1023 Python2班
1024 Python2班
1025 Python2班
1001 大数据1班
*/