-1

如何获得表中每年的最高值。所以假设我们有一张桌子movies,我想找到每年利润最高的电影。

这是我迄今为止的尝试:

SELECT year, MAX(income - cost) AS profit, title
FROM Movies m, Movies m2
GROUP BY year

我很确定它需要一些子选择,但我无法想象我需要做什么。distinct我也在考虑可能排除重复年份的某种选择。

Title  Year   Income  Cost  Length
A      2000   10      2     2
B      2000   9       7     2

因此,由此预期的结果将是

Title  Year   Profit
A      2000   8
4

3 回答 3

1

我稍微猜测您想要什么,但由于您没有指定任何 RDBMS,通用解决方案将是:

SELECT  m.Year, (m.Income - m.Cost) AS Profit, m.Title
FROM    Movies m
        INNER JOIN
        (   SELECT  m.Year, MAX(m.Income - m.Cost) AS Profit
            FROM    Movies
            GROUP BY m.Year
        ) MaxProfit
            ON MaxProfit.Year = m.Year
            AND MaxProfit.Profit = (m.Income - m.Cost)
ORDER BY m.Year

如果您的 DBMS 允许,您也可以使用分析函数来执行此操作。例如 SQL 服务器

WITH MovieCTE AS
(   SELECT  m.Year,
            Profit = (m.Income - m.Cost), 
            m.Title,
            RowNumber = ROW_NUMBER() OVER(PARTITION BY m.Year ORDER BY (m.Income - m.Cost) DESC)
    FROM    Movies
)
SELECT  year, Profit, Title
FROM    MovieCTE
WHERE   RowNumber = 1

我可能误解了您的确切标准,但我确信可以应用相同的原则,您只需要更改第一个示例或partition by第二个示例中的分组和连接。

于 2012-10-25T14:08:27.807 回答
0
select m1year,m1profit,title 
from 
(
  (select year as m1year, max(income- cost) as m1profit from movies group by year) m1
   join
  (select m2year, (income-cost) as m2profit ,title as profit from movies) m2
   on 
   m1profit = m2profit
) m
于 2012-10-25T14:08:56.190 回答
0

这将给出每年利润最高的电影,并在出现平局时选择第一个标题:

 select a.year, a.profit,
    (select min(title) from Movies where year = a.year and income - cost = a.profit) as title
 from ( 
     select year, max(income - cost) as profit
     from Movies -- title, year, cost, income, number
     group by year
) as a
order by year desc
于 2012-10-25T14:09:25.557 回答