TSQL显示条件中具有计数列的列的字段值

时间:2015-10-03 19:51:23

标签: sql-server count

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

(select col1, col2, count(col3)
from table1
group by col1,col2
Having count(col3) < 50) 

但我想显示col3的所有字段值,其中count(col3)&lt; 50。你能帮帮我吗?谢谢

2 个答案:

答案 0 :(得分:0)

试试这个:

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 BYCOUNT(col3) OVER (PARTITION BY col1, col2)会为col3的每一行返回col1, col2 table1次出现次数。您可以在外部查询中过滤掉计数为50或更多的col1, col2个切片。

答案 1 :(得分:0)

您也可以使用以下内容:

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