某一个字段在数据表中出现的数量次数多少然后排序

来源:百度知道 编辑:UC知道 时间:2024/06/05 07:42:13
id user_id sales(数字型)
2 5 5
3 1 6
4 1 3
5 1 3
6 2 3
7 3 3
8 1 6

数据库结构是这样的,id为自动增长的。现在想根据 sales 中由多到少排列。
比如上面的排列就是:
第一名是: sales为 3 的 总数:4
第二名是: sales为 6 的 总数:2
第三名是: sales为 5 的 总数:1

还是这样显示

use Tempdb
go
--> -->

declare @T table([id] int,[user_id] int,[sales] int)
Insert @T
select 2,5,5 union all
select 3,1,6 union all
select 4,1,3 union all
select 5,1,3 union all
select 6,2,3 union all
select 7,3,3 union all
select 8,1,6

Select * from @T t order by (select count(1) from @T where [sales]=t.[sales]) desc,ID asc

(7 个资料列受到影响)
id user_id sales
----------- ----------- -----------
4 1 3
5 1 3
6 2 3
7 3 3
3 1 6
8 1 6
2 5 5

(7 个资料列受到影响)

select sales,count(1)
from 表
group by sales
order by count(1) desc

SQL语句:
select sales,count(id) as 'shuliang'
from 表名
group by sales
order by shuliang desc

select sales