Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query Help: Selecting Rows That Appear A Certain Number Of Times

Tags:

date

sql

select

I have a table with a "Date" column. Each Date may appear multiple times. How do I select only the dates that appear < k number of times?

like image 753
Jake Avatar asked Sep 19 '08 19:09

Jake


3 Answers

SELECT * FROM [MyTable] WHERE [Date] IN
(
    SELECT [Date] 
    FROM [MyTable] 
    GROUP By [Date] 
    HAVING COUNT(*) < @Max
)

See @[SQLMenace] 's response also. It's very similar to this, but depending on your database his JOIN will probably run faster, assuming the optimizer doesn't make the difference moot.

like image 140
Joel Coehoorn Avatar answered Oct 01 '22 00:10

Joel Coehoorn


select dates 
  from table t 
 group by dates having count(dates) < k ;

Hopefully, it works for ORACLE. HTH

like image 33
Zsolt Botykai Avatar answered Sep 30 '22 23:09

Zsolt Botykai


Use the COUNT aggregate:

SELECT Date
FROM SomeTable
GROUP BY Date
HAVING COUNT(*) < @k
like image 26
Ihar Bury Avatar answered Oct 01 '22 01:10

Ihar Bury