Sql server TSQL显示条件为count column的列的字段值

Sql server TSQL显示条件为count column的列的字段值,sql-server,count,Sql Server,Count,我有一个查询,它将对第1列和第2列进行分组,并计算第3列的计数 (select col1, col2, count(col3) from table1 group by col1,col2 Having count(col3) < 50) 但我想显示col3的所有字段值,其中countcol3

我有一个查询,它将对第1列和第2列进行分组,并计算第3列的计数

(select col1, col2, count(col3)
from table1
group by col1,col2
Having count(col3) < 50) 
但我想显示col3的所有字段值,其中countcol3<50。你能帮我吗?谢谢

试试这个:

select col1, col2, col3, t.cnt 
from (
  select col1, col2, col3, 
         count(col3) over (partition by col1, col2) AS cnt
  from table1 ) as t
where t.cnt < 50
其思想是使用COUNT的窗口版本,而不是GROUP BY。COLL3 OVER PARTITION BY col1,col2返回表1中每一行col1、col2中col3出现的次数。您可以在外部查询中筛选出计数为50或更多的col1、col2切片。

尝试以下操作:

select col1, col2, col3, t.cnt 
from (
  select col1, col2, col3, 
         count(col3) over (partition by col1, col2) AS cnt
  from table1 ) as t
where t.cnt < 50

其思想是使用COUNT的窗口版本,而不是GROUP BY。COLL3 OVER PARTITION BY col1,col2返回表1中每一行col1、col2中col3出现的次数。您可以在外部查询中筛选出计数为50或更多的col1、col2切片。

您也可以使用类似的方法:

select t.col1, t.col2, t.col3
from table1 t
where
EXITS(select 1 from table1 t1 where t.col1 = t1.col1 and t.col2 = t.col2 having count(t1.col3) > 50)
select t.col1, t.col2, t.col3
from table1 t
inner join (select t1.col1, t1.col2, count(t1.col3) from table1 t1 
group by t1.col1, t1.col2 having count(t1.col3) > 50) x
on t.col1 = x.col1 and t.col2 = x.col2
或者像这样:

select t.col1, t.col2, t.col3
from table1 t
where
EXITS(select 1 from table1 t1 where t.col1 = t1.col1 and t.col2 = t.col2 having count(t1.col3) > 50)
select t.col1, t.col2, t.col3
from table1 t
inner join (select t1.col1, t1.col2, count(t1.col3) from table1 t1 
group by t1.col1, t1.col2 having count(t1.col3) > 50) x
on t.col1 = x.col1 and t.col2 = x.col2

您也可以使用类似以下内容:

select t.col1, t.col2, t.col3
from table1 t
where
EXITS(select 1 from table1 t1 where t.col1 = t1.col1 and t.col2 = t.col2 having count(t1.col3) > 50)
select t.col1, t.col2, t.col3
from table1 t
inner join (select t1.col1, t1.col2, count(t1.col3) from table1 t1 
group by t1.col1, t1.col2 having count(t1.col3) > 50) x
on t.col1 = x.col1 and t.col2 = x.col2
或者像这样:

select t.col1, t.col2, t.col3
from table1 t
where
EXITS(select 1 from table1 t1 where t.col1 = t1.col1 and t.col2 = t.col2 having count(t1.col3) > 50)
select t.col1, t.col2, t.col3
from table1 t
inner join (select t1.col1, t1.col2, count(t1.col3) from table1 t1 
group by t1.col1, t1.col2 having count(t1.col3) > 50) x
on t.col1 = x.col1 and t.col2 = x.col2

工作得很好!谢谢你,我很惊讶你这么快的回答真的很好!谢谢你,我很惊讶能这么快回答。在我做了一些小改动后,这个解决方案也起了作用。非常感谢。伙计们,你们真的很完美。在我做了一些小改动后,这个解决方案也起了作用。非常感谢。伙计们,你们真的很完美。