gpt4 book ai didi

sql - MySQL - 如何检索同一行中的列作为 min/mx 返回的值

转载 作者:行者123 更新时间:2023-11-29 07:13:42 27 4
gpt4 key购买 nike

我无法正确构建问题的标题。假设每周电影收入表如下:

MovieName  <Varchar(450)>
MovieGross <Decimal(18)>
WeekofYear <Integer>
Year <Integer>

那么,如果我这样做,我该如何获得今年每周的最高票房收入:

    select MovieName , Max(MovieGross) , WeekofYear 
from earnings where year = 2010 group by WeekofYear;

那么显然查询不会运行,而

    select Max(MovieName) , Max(MovieGross) , WeekofYear 
from earnings where year = 2010 group by WeekofYear;

只会给出以最低字母开头的电影。使用 group_concat() 然后使用 substring_index() 是唯一的选择吗?

    select 
substring_index(group_concat(MovieName order by MovieGross desc),',',1),
Max(MovieGross) , WeekofYear from earnings where year = 2010
group by WeekofYear ;

看起来很笨拙。有没有更好的方法来实现这一目标?

最佳答案

这是不断重复出现的每组最大值问题。您可以通过选择您的组的定义属性然后加入您的“真实”数据来解决它。

select 
e.MovieName,
e.MovieGross,
e.WeekofYear
from
earnings e
inner join (
select Max(MovieGross) MovieGross, Year, WeekofYear
from earnings
group by Year, WeekofYear
) max on max.Year = e.Year
and max.WeekofYear = e.WeekofYear
and max.MovieGross = e.MovieGross
where
e.year = 2010

您组的定义属性是YearWeekofYearMAX(MovieGross)。每个组范围将有一行具有不同的值。

针对您的数据表的 INNER JOIN 会排除所有不满足您的组定义属性的行。这也意味着它允许通过所有行 - 您最终可能会得到两部电影在任何特定的一周内赚取相同数量的钱。再次对“外部”查询进行分组以消除重复的行以支持单部电影。

关于sql - MySQL - 如何检索同一行中的列作为 min/mx 返回的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2828507/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com