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.
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.
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.
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.
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).
Use the Group By
clause with Having
:
SELECT id
FROM dbo.TableName
GROUP BY ID
HAVING COUNT(*) >= 3
Demo
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With