I have the following db diagram :
I want to find the decade (for example 1990 to 2000) that has the most number of movies. Actually it only deals with "
You can use the LEFT function in SQL Server to get the decade from the year. The decade is the first 3 digits of the year. You can group by the decade and then count the number of movies. If you sort, or order, the results by the number of movies - the decade with the largest number of movies will be at the top. For example:
select
count(id) as number_of_movies,
left(cast([year] as varchar(4)), 3) + '0s' as decade
from movies
group by left(cast([year] as varchar(4)), 3)
order by number_of_movies desc
select substring(cast([year] as varchar), 1, 3) as Decade,
Count(1) [Count]
from Movies
group by substring(cast([year] as varchar), 1, 3)
order by 2 desc
An alternative to the string approach is to use integer division to get the decade:
SELECT [Year]/10*10 as [Decade]
, COUNT(*) as [CountMovies]
FROM Movies
GROUP BY [Year]/10*10
ORDER BY [CountMovies] DESC
This returns all, ordered by the decade(s) with the most movies. You could add a TOP (1) to only get the top, but then you'd need to consider tiebreaker scenarios to ensure you get deterministic results.
SELECT floor(Year(getdate())/10)*10
, floor(year('5/11/2004')/10)*10
, floor(Year('7/23/1689')/10)*10
, floor(Year('7/09/1989')/10)*10