仅从表中选择字段值重复小于x次的记录

时间:2014-04-24 16:48:57

标签: sql sql-server

我是SQL的新手,如果你能帮助我,我将不胜感激。我有一个表有一个具有许多ID的字段,该字段是数字格式。相同的ID可以重复不同的次数,例如5次,6次。我希望仅在相同ID在此字段中重复少于x次时才显示所有字段的记录。哪个sql语句会完成这个?

提前致谢。

3 个答案:

答案 0 :(得分:4)

试试这个:

SELECT T1.* FROM TableName T1
INNER JOIN 
(SELECT ID,COUNT(ID) as Count
FROM TableName
GROUP BY ID
HAVING COUNT(ID) < 5) T2 ON T1.ID=T2.ID

修改

使用别名尝试查询:

SELECT APropertyID,BPropertyID,Ayy,Byy from 
(SELECT a.PropertyID as APropertyID, b.PropertyID as BPropertyID, a.yy as Ayy,b.yy  as Byy
FROM tableA a full outer join 
     tableB b on a.PropertyID=b.PropertyID ) a1 
inner join 
(SELECT PropertyID,COUNT(PropertyID) as Count 
FROM tableA 
GROUP BY PropertyID 
HAVING COUNT(PropertyID) < 5) c 
on a1.APropertyID=c.PropertyID

答案 1 :(得分:0)

SQL Server允许在聚合中使用OVER Clause(这是一个非常有用但非标准的#34; SQL功能),在这种情况下很方便。

  

在应用关联的窗口函数之前确定行集的分区和排序。也就是说,OVER子句定义查询结果集中的窗口或用户指定的行集。然后,窗口函数计算窗口中每行的值。您可以将OVER子句与函数一起使用来计算聚合值,例如移动平均值,累积聚合,运行总计或每组结果的前N个。

示例:

SELECT cts.*
FROM (
    -- Build intermediate result where each record also has
    -- a count of how many times that value appears.
    SELECT
        t.*,
        COUNT (1) OVER (PARTITION BY value) as valueCount
    FROM t
) as cts
-- Filter intermediate result based on collected count.
WHERE cts.valueCount < 5

(我已使用value代替上面的ID - 同样的方法也适用。)

答案 2 :(得分:0)

SELECT * 
FROM MyTable
WHERE ID IN
  (SELECT ID
  FROM MyTable
  GROUP BY ID
  HAVING COUNT(1) < 5)