SQL:如何列出不是同一列的5个最高值的列的值?

时间:2015-08-07 03:13:55

标签: sql-server sql-server-2012 subquery

我理解如何显示列中最常出现的5个值:

select top 5 col1, count(col1)
from table1
group by col1
order by count(col1) desc; 

但是,如何创建一个查询,显示同一列中不属于上述查询结果的所有其他值?

我尝试了以下子查询:

select col1
from table1
where col1 not in 
    (select top 5 col1, count(col1)
     from table1
     group by col1
     order by count(col1) desc);

但是查询失败,我收到以下错误消息:

  

当选择列表中只能指定一个表达式时   子查询不是用EXISTS引入的。

3 个答案:

答案 0 :(得分:1)

对于Sql Server 2012+,您可以使用offset

select col1, count(col1)
from table1
group by col1
order by count(col1) desc
offset 5 rows

您可能希望在此处为您的订购添加决胜局,以使其具有确定性:

select col1, count(col1)
from table1
group by col1
order by count(col1) desc, col1
offset 5 rows

答案 1 :(得分:0)

问题是您无法在subquery内选择多个列。

(select top 5 col1, count(col1)..

您可以从子查询中删除count(col1),但NOT IN col1中的subquery NULL

时,with cte as ( select top 5 col1 from table1 group by col1 order by count(col1) desc ) select * from table1 A where not exists (select 1 from cte B where a.Col=b.col) 子句可能会失败

尝试像这样改变

normalize-space(.//div[@class="jt_jobs_title"]/text())
            HERE^

答案 2 :(得分:0)

使用OFFSET

select col1, count(col1)
from table1
group by col1
order by count(col1) desc
OFFSET 5 ROWS -- skip 5 rows, must use with order by