Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only return rows where the value appears more than n times

Suppose I have a table

  id            value
------        ---------
  A              123
  A              422
  B              441
  B              986
  B              674
  C              648

I need a query which will return only those id's which have 3 or more values associated with them. So, in that case it will only return B. Thank you.

like image 292
Dzmitry Sevkovich Avatar asked Nov 12 '13 21:11

Dzmitry Sevkovich


People also ask

How do you check if value appears more than once in SQL?

To find duplicate values in SQL, you must first define your criteria for duplicates and then write the query to support the search. In order to see how many of these names appear more often than others, you could add an additional ORDER BY statement to the end of the query and order by DESC.

Which clause is used to return specific rows?

The WHERE clause allows you to retrieve only rows you are interested in. If the expression in the WHERE clause is true for any row, then that row is returned.

Which function returns the number of rows in a result set?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values.

Which clause is used on multiple rows?

Multiple-row subqueries are used most commonly in WHERE and HAVING clauses. Since it returns multiple rows, it must be handled by set comparison operators (IN, ALL, ANY).


2 Answers

Use the Group By clause with Having:

SELECT id 
FROM dbo.TableName
GROUP BY ID
HAVING COUNT(*) >= 3

Demo

like image 144
Tim Schmelter Avatar answered Nov 06 '22 13:11

Tim Schmelter


In case you want to include the value, you can use window functions to find the ones with three or more rows, e.g.:

DECLARE @x TABLE(id CHAR(1), value INT);

INSERT @x SELECT 'A',       123;
INSERT @x SELECT 'A',       422;
INSERT @x SELECT 'B',       441;
INSERT @x SELECT 'B',       986;
INSERT @x SELECT 'B',       674;
INSERT @x SELECT 'C',       648;

;WITH x AS 
(
  SELECT id, value, rn = ROW_NUMBER() OVER (PARTITION BY id ORDER BY id)
  FROM @x
)
SELECT id FROM x WHERE rn = 3;

And you can change the ORDER BY to help better determine which value is included.

like image 41
Aaron Bertrand Avatar answered Nov 06 '22 12:11

Aaron Bertrand