TSQL 显示条件中包含计数列的列的字段值
TSQL display field values for column with count column in condition
我有一个查询,它将第 1 列和第 2 列分组并计算第 3 列的计数
(select col1, col2, count(col3)
from table1
group by col1,col2
Having count(col3) < 50)
但我想显示 col3 的所有字段值,其中 count(col3) < 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
。 COUNT(col3) OVER (PARTITION BY col1, col2)
returns col1, col2
table1
的每一行 出现 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
我有一个查询,它将第 1 列和第 2 列分组并计算第 3 列的计数
(select col1, col2, count(col3)
from table1
group by col1,col2
Having count(col3) < 50)
但我想显示 col3 的所有字段值,其中 count(col3) < 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
。 COUNT(col3) OVER (PARTITION BY col1, col2)
returns col1, col2
table1
的每一行 出现 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