TSQL的count问题

kingmeta 2012-02-10 05:03:21
id username Point
1 张三 100
2 李四 100
3 张三 100
4 张三 100
5 赵大 100
6 赵大 100

如果能得出以下结果

张三 3
赵大 2
李四 1

注意要从大到小排序,排序是按记录数的多少排的
...全文
88 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
lwqhp 2012-02-10
  • 打赏
  • 举报
回复

--分组,然后按记录数排序
select username,count(*) as count
from tb
group by username
order by count desc
勿勿 2012-02-10
  • 打赏
  • 举报
回复
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 行受影响)
Felixzhaowenzhong 2012-02-10
  • 打赏
  • 举报
回复
select distinct username,count(*) from tb group by username order by count(*) desc --只有 ORDER BY 中可以使用别名
叶子 2012-02-10
  • 打赏
  • 举报
回复

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
*/
dawugui 2012-02-10
  • 打赏
  • 举报
回复
select username , count(1) cnt from tb group by username order by cnt desc
唐诗三百首 2012-02-10
  • 打赏
  • 举报
回复

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)
geniuswjt 2012-02-10
  • 打赏
  • 举报
回复

select username,count(1) from tb
group by username
order by 2 desc
q806294478 2012-02-10
  • 打赏
  • 举报
回复
select username,count(*) from tb group by username order by count(*) desc

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧