我有一个如下所示的表结构:
ClassId
ClassDescription
我的表格数据如下:
ClassId ClassDesc
4 ---
4 ---
4 ---
4
4
2
2
2
现在我要做的是根据每个classId
含义得到classId
的计数,例如,上面的表将为所有classId返回5的计数=对于classId = 2,计数为3,
所以我的Sql语句单独计算它们并按顺序计数DESC对ClassId的计数
4计数到5
2计数到3
最终输出应如下所示:
ClassId ClassDesc
4 ----
2 ----
答案 0 :(得分:0)
使用分组依据
SELECT classID, ClassDescription FROM
(SELECT classID, ClassDescription, COUNT(1) cnt FROM mytable GROUP
BY classID, ClassDescription) AS A
ORDER BY cnt DESC
OR
SELECT classID, ClassDescription FROM <table> GROUP BY classID, ClassDescription
ORDER BY COUNT(1) DESC
答案 1 :(得分:0)
试试这个:
SELECT ClassId, COUNT(ClassDesc) AS ClassDesc
FROM MyTable
GROUP BY ClassId
ORDER BY COUNT(ClassDesc) DESC;
输出:
╔═════════╦═══════════╗
║ CLASSID ║ CLASSDESC ║
╠═════════╬═══════════╣
║ 4 ║ 5 ║
║ 2 ║ 3 ║
╚═════════╩═══════════╝
答案 2 :(得分:0)
你的问题标题是你的答案,你只需付出一些努力。
您想尝试以下内容:
declare @temp table
(
classid int,
classdesc varchar(10)
)
insert into @temp
select 4, 'test'
union all
select 4, 'test1'
union all
select 4, 'test2'
union all
select 4, 'test 3'
union all
select 4, 'test 4'
union
select 2, 'test'
union
select 2, 'test 2'
select classid, count(*) classcount
from @temp
group by classid
order by classcount desc
我希望它有所帮助!