按字段计数的顺序问题

时间:2013-05-09 05:36:02

标签: sql sql-server-2008 count sql-order-by

我有一个如下所示的表结构:

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           ----

3 个答案:

答案 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 ║
╚═════════╩═══════════╝

See this SQLFiddle

答案 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

我希望它有所帮助!