简体   繁体   中英

SQL Select Query Group By With Key (Join or SubQuery)

Trying to wrap my head around this query but here it is...

Table: TVEpisode
Columns: TVEpisodeID (PK), TVSeriesID, season (number), episode (number), watched (0 or 1)

What I am looking to get is the first unwatched (value 0) episode for each TVSeries. For example, if I have watched all of season 1 for a TVSeriesID (45) and my lasted watched episode is season 2 episode 5, I want the query to return:

TVEpisodeID | TVSeriesID | Season | Episode
PK          | 45         | 2      | 6

Need that result for each TVSeries

In most databases, you would do this with the ANSI standard window functions:

select tve.*
from (select tve.*
             row_number() over (partition by tvseriesid order by season, episode) as seqnum
      from tvepisode tve
      where tve.watched = 0
     ) tve
where seqnum = 1;

I assume that "first" is referring to the combination of season and episode .

This should give you first watched=0 of all season/episode combination

SELECT *
FROM TVEpisode
WHERE TVEpisodeID IN
    ( SELECT min(TVEpisodeID)
     FROM TVEpisode
     WHERE watched=0
     GROUP BY TVSeriesID) t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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