34,590
社区成员
发帖
与我相关
我的任务
分享
--分组,然后按记录数排序
select username,count(*) as count
from tb
group by username
order by count desc
if OBJECT_ID('tb') is not null
drop table tb
go
create table tb(id int, username varchar(50), Point int)
insert into tb
select 1, '张三', 100 union all
select 2, '李四', 100 union all
select 3, '张三', 100 union all
select 4, '张三', 100 union all
select 5, '赵大', 100 union all
select 6, '赵大', 100
select username,COUNT(*)as 次数 from tb group by username order by 次数 desc
username 次数
-------------------------------------------------- -----------
张三 3
赵大 2
李四 1
(3 行受影响)
declare @T table (id int,username varchar(4),Point int)
insert into @T
select 1,'张三',100 union all
select 2,'李四',100 union all
select 3,'张三',100 union all
select 4,'张三',100 union all
select 5,'赵大',100 union all
select 6,'赵大',100
--1.group by
select username,count(1) cnt from @t group by username order by 2 DESC
--2.子查询
select distinct username,
(select count(1) from @t where username=t.username) cnt
from @t t order by 2 desc
--3.count+over
select distinct username,count(1) over (partition by username) from @t
order by 2 DESC
/*
username cnt
-------- -----------
张三 3
赵大 2
李四 1
*/
create table kin
(id int, username varchar(8), Point int)
insert into kin
select 1, '张三', 100 union all
select 2, '李四', 100 union all
select 3, '张三', 100 union all
select 4, '张三', 100 union all
select 5, '赵大', 100 union all
select 6, '赵大', 100
select username,count(*) ct
from kin
group by username
order by count(*) desc
username ct
-------- -----------
张三 3
赵大 2
李四 1
(3 row(s) affected)
select username,count(1) from tb
group by username
order by 2 desc
select username,count(*) from tb group by username order by count(*) desc