当第 3 列在一个查询中具有特定值时,如何查询所有行但限制两列的最大值?

How do I query for all rows but limit by max values of two columns when 3rd column is of a specific value in one single query?

ID     Type     MovieYear      MovieName    BookName       BookGenre     SongName     SongYear     SongMonth
-------------------------------------------------------------------------------------------------------------
1      Book     null           null         The Hobbit     Fantasy       null          null        null
2      Movie    2019           It           null           null          null          null        null   
3      Song     null           null         null           null          Desperado     2019        11
4      Song     null           null         null           null          Desperado     2019        7
5      Song     null           null         null           null          Away          2000        6
6      Song     null           null         null           null          Away          1988        10

鉴于以上数据,我需要能够进行单个查询。如果 type 是 not 'Song' 那么我想获取那些非歌曲类型的所有内容,如果 type is 'Song,' 然后我只想获取包含每个唯一 'SongName' 但获取 Max 'SongYear' 以及 Max 'SongMonth'

的那些行

我希望我的结果是:

ID     Type     MovieYear      MovieName    BookName       BookGenre     SongName     SongYear     SongMonth
-------------------------------------------------------------------------------------------------------------
1      Book     null           null         The Hobbit     Fantasy       null          null        null
2      Movie    2019           It           null           null          null          null        null   
3      Song     null           null         null           null          Desperado     2019        11
5      Song     null           null         null           null          Away          2000        6

这是我目前尝试过的方法:

SELECT * FROM mytable
WHERE ID IN (
    SELECT ID FROM mytable
    WHERE (songname, songyear, songmonth) IN (
         SELECT songname, max(songyear), max(songmonth)
         FROM (
                  SELECT songname, songyear, songmonth
                  FROM mytable
                  WHERE type = 'Song'
                  GROUP BY songname, songyear, songmonth
         )
         GROUP BY songname
    )
)

显然这个查询非常复杂而且非常慢,而且它也没有考虑到在这个单一查询中还需要获取 Book 和 Movie 类型。关于我应该尝试哪种类型的查询有什么想法吗?

嗯。 . .我认为 row_number() 这样做:

select t.*
from (select t.*,
             row_number() over (partition by type, songname order by songyear desc, songmonth desc) as seqnum
      from mytable t
     ) t
where type <> 'Song' or seqnum = 1;