SQL:如何列出不是同一列中出现次数最多的 5 个值的列的值?

SQL: how to list values of a column that are not the 5 most occurring value of that same column?

我了解如何像这样显示列中出现次数最多的 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);

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

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

问题是您不能 select 在 subquery 中超过一列。

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

您可以从子查询中删除 count(col1),但是当 subquery 中的 col1 具有 NULL 值时 NOT IN 子句可能会失败

试试这样改

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)

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

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