Reputation: 203
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, e.g. 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.
Upvotes: 1
Views: 504
Reputation: 18747
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
Upvotes: 5
Reputation: 10013
SELECT *
FROM MyTable
WHERE ID IN
(SELECT ID
FROM MyTable
GROUP BY ID
HAVING COUNT(1) < 5)
Upvotes: 0
Reputation: 61935
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.)
Upvotes: 0