首先是SQL Server组取消组合?

时间:2012-11-29 20:04:11

标签: sql sql-server group-by

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

AA
AA
BB
CCC
CCC
CCC

返回

AA  1
AA  1
BB  1
CCC 3

感谢您的帮助

3 个答案:

答案 0 :(得分:3)

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的答案更快。

答案 1 :(得分: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

答案 2 :(得分: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)。