简体   繁体   中英

Select records from a table only where a field value is repeated less than x times

I am very new to SQL and I would appreciate it if you could help me. I have a table that has a field with many IDs and that field is in number format. The same ID may repeat different number of times, eg 5 times, 6 times. I want to display records of all fields only when the same ID is repeated less than x times in this field. Which sql statement will get this done?

Thanks in advance.

Try this:

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

EDIT:

Try your query using alias names:

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

SQL Server allows for an OVER Clause in aggregates (which is a useful but "nonstandard" SQL feature) that is handy in cases like this.

Determines the partitioning and ordering of a rowset before the associated window function is applied. That is, the OVER clause defines a window or user-specified set of rows within a query result set. A window function then computes a value for each row in the window. You can use the OVER clause with functions to compute aggregated values such as moving averages, cumulative aggregates, running totals, or a top N per group results.

Example:

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

(I've used value instead of ID above - the same approach holds.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM