1

我有一个需要分组的数据列表,但我们只想对计数大于 3 的数据进行分组。

AA
AA
BB
CCC
CCC
CCC

返回

AA  1
AA  1
BB  1
CCC 3

感谢您的帮助

4

3 回答 3

4
select data, case when total < 3 then 1 else total end total
from
    (
        select data, Count(Data) Total
        from tbl
        group by data
    ) g
join (select 1 union all select 2) a(b)
  on a.b <= case when total < 3 then Total else 1 end
order by data

大多数情况下,这应该比 LittleBobbyTables 的答案执行得更快。

于 2012-11-29T20:25:36.250 回答
2

在我的脑海中,您可以使用获取计数大于 2 的所有内容的计数,然后用于UNION ALL获取不在第一个查询中的任何记录:

SELECT 'AA' AS Data
INTO #Temp
UNION ALL SELECT 'AA'
UNION ALL SELECT 'BB'
UNION ALL SELECT 'CCC'
UNION ALL SELECT 'CCC'
UNION ALL SELECT 'CCC'

SELECT Data, COUNT(Data) AS MyCount
FROM #Temp
GROUP BY Data
HAVING COUNT(Data) > 2

UNION ALL

SELECT Data, 1
FROM #Temp
WHERE Data NOT IN (
    SELECT Data
    FROM #Temp
    GROUP BY Data
    HAVING COUNT(Data) > 2
)
ORDER BY Data

DROP TABLE #Temp
于 2012-11-29T20:15:54.693 回答
0

为此使用窗口函数:

select col, count(*) as cnt
from (select col, count(*) over (partition by col) as colcnt,
             row_number() over (order by (select NULL)) as seqnum
      from t
     ) t
 group by col, (case when colcnt < 3 then seqnum else NULL end)

这将计算列的总计数和每行的唯一标识符。然后 group by 子句测试条件。如果小于 3,则它使用标识符来获取每一行。如果更大,则在这种情况下使用常量值 (NULL)。

于 2012-11-29T21:36:36.893 回答