MSSql仅对计数大于3的那些进行分组并返回其余记录

时间:2014-11-10 22:19:21

标签: sql-server group-by conditional

我想将计数大于3的密钥分组,查询也将返回其余记录。我不想使用Union All,还有其他办法吗?

ID
1
1
1
2
3
3
4
4
4
4个

返回
1
1
1
2
3
3
4个

2 个答案:

答案 0 :(得分:3)

您可以使用ranking- and aggregate functions

WITH CTE AS
(
  SELECT ID, 
         CNT = COUNT(*)     OVER (PARTITION BY ID),
         RN  = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID)
  FROM dbo.TableName
)
SELECT ID
FROM CTE
WHERE CNT <= 3 OR RN = 1

Demo

答案 1 :(得分:0)

我会这样做

SELECT 
GroupedData.ID
FROM 
    (SELECT ID, CNT = COUNT(*)
    FROM dbo.TableName
    GROUP BY ID) GroupedData AS g
LEFT JOIN dbo.TableName AS  t
ON t.id = g.id and g.CNT<=3

这也允许您添加更多列,以便根据需要报告组或单个记录的详细信息

SELECT 
g.ID, 
ISNULL(t.RecordName,'Grouped Records') as RecordName,
ISNULL(t.NumericField,g.NumericField)  as NumericField
FROM 
    (
     SELECT ID, CNT = COUNT(*), SUM(NumericField) as NumericField
     FROM dbo.TableName
     GROUP BY ID
    ) GroupedData AS g
LEFT JOIN dbo.TableName AS  t
ON t.id = g.id and g.CNT<=3