Finding the decade with largest records, SQL Server

前端 未结 4 964
我寻月下人不归
我寻月下人不归 2021-01-06 17:13

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 "

相关标签:
4条回答
  • 2021-01-06 17:24

    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
    
    0 讨论(0)
  • 2021-01-06 17:33
    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
    
    0 讨论(0)
  • 2021-01-06 17:47

    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.

    0 讨论(0)
  • 2021-01-06 17:48
       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
    
    0 讨论(0)
提交回复
热议问题