简体   繁体   English

查找记录最多的十年,SQL Server

[英]Finding the decade with largest records, SQL Server

I have the following db diagram :我有以下数据库图:

电影数据库图

I want to find the decade (for example 1990 to 2000) that has the most number of movies.我想找到电影数量最多的十年(例如 1990 年到 2000 年)。 Actually it only deals with "Movies" table.实际上它只处理“电影”表。

Any idea on how to do that?关于如何做到这一点的任何想法?

You can use the LEFT function in SQL Server to get the decade from the year.您可以使用 SQL Server 中的 LEFT 函数来获取年份的十年。 The decade is the first 3 digits of the year.十年是一年的前 3 位数字。 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

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.您可以添加 TOP (1) 以仅获得顶部,但随后您需要考虑决胜局方案以确保获得确定性结果。

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
   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

Despite being an old question I found this solution via trying尽管这是一个老问题,但我通过尝试找到了这个解决方案

    DATE_PART('decade',(year::date)) AS decade,
    DATE_TRUNC('decade',(year::date)) AS decade_truncated,

also works for也适用于

    DATE_PART('century',(year::date)) AS decade,
    DATE_TRUNC('century',(year::date)) AS decade_truncated,

In my case, I am having year as a string column.就我而言,我将year作为字符串列。 To get the movies grouped by decades,为了让电影按几十年分组,

SELECT DISTINCT NUMRANGE(
CAST(FLOOR(CAST(year AS INT)/ 10) * 10 AS INT),
CAST((FLOOR(CAST(year AS INT)/ 10) * 10) + 9 AS INT)
) AS "decades", COUNT(*) AS "movie_count"
FROM movies
WHERE year IS NOT NULL AND year != ''
GROUP BY decades
ORDER BY movie_count DESC;

This gives the number of movies in that decade.这给出了那十年的电影数量。 Hope this one helps someone...希望这个可以帮助某人...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM