SQL Query: Need order by count, most must be on top, the rest follows

て烟熏妆下的殇ゞ 提交于 2019-12-03 14:12:19

SQL Server 2008 using COUNT() OVER

select *, c = count(1) over (partition by zip)
from tbl
order by c desc;

If you don't need to see the additional column, then you can move the COUNT() OVER clause into the ORDER BY clause.

select JobCode, Job1, Job2, Job3, zip
from tbl
order by count(1) over (partition by zip) desc;

To accomplish this, you should join against a subquery which returns the count per zipcode. The joined subquery is only needed to provide the counts (even if not displayed), while the main table yourtable provides all the rest of the columns.

SELECT 
  JobCode, 
  Job1,
  Job2,
  Job3,
  subq.zip
FROM
  yourtable
  JOIN (
     /* Subquery returns count per zip group */
     SELECT zip, COUNT(*) AS numzip 
     FROM yourtable 
     GROUP BY zip
  ) subq ON yourtable.zip = subq.zip
ORDER BY numzip DESC
SELECT 
  JobCode, Job1, Job2, Job3, order_jobs.zip
FROM
  jobs
  JOIN (SELECT zip, COUNT(*) AS zipcount FROM jobs GROUP BY zip) ordering 
ON jobs.zip = ordering.zip
ORDER BY zipcount DESC
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!