我有一个包含这些列的表:
id | series_id | season_id | episode_id | title | type ...
我想获得具有唯一series_id
位置season_id
和episode_id
最大值的行。
一种解决方案是这样做:
SELECT t1.*
FROM YourTable AS t1
INNER JOIN
(
SELECT
series_id,
MAX(season_id) AS MAxSeasonId,
MAX(Episode_id) AS MAXEpisodeID
FROM yourTable
GROUP BY series_id
) AS t2 ON t1.series_id = t2.series_id
AND t1.season_id = t2.MaxSeasonId
AND t1.episode_id = t2.MaxEpisode_id;
我认为这可能有点矫枉过正,但这是我发现对我有用的唯一方法。
DECLARE @SeriesInfo TABLE
(
id INT,
series_id INT,
season_id INT,
episode_id INT,
title VARCHAR(50),
type CHAR(1)
);
INSERT INTO @SeriesInfo VALUES ( 1, 1, 1, 1, 'Series 1 Season 1 Episode 1', 'A'),
( 2, 1, 1, 2, 'Series 1 Season 1 Episode 2', 'A'),
( 3, 1, 1, 3, 'Series 1 Season 1 Episode 3', 'A'),
( 4, 1, 2, 1, 'Series 1 Season 2 Episode 1', 'A'),
( 5, 1, 2, 2, 'Series 1 Season 2 Episode 2', 'A'),
( 6, 2, 1, 1, 'Series 2 Season 1 Episode 1', 'A'),
( 7, 2, 1, 2, 'Series 2 Season 1 Episode 2', 'A'),
( 8, 2, 1, 3, 'Series 2 Season 1 Episode 3', 'A'),
( 9, 2, 1, 4, 'Series 2 Season 1 Episode 4', 'A'),
(10, 2, 2, 1, 'Series 2 Season 2 Episode 1', 'A'),
(11, 2, 2, 2, 'Series 2 Season 2 Episode 2', 'A'),
(12, 2, 2, 3, 'Series 2 Season 2 Episode 3', 'A');
SELECT id,
series_id,
season_id,
episode_id,
title,
type
FROM (
SELECT ROW_NUMBER() OVER(PARTITION BY series_id ORDER BY season_id DESC, episode_id DESC) RowNum,
*
FROM @SeriesInfo
) X
WHERE X.RowNum = 1;
--SELECT ROW_NUMBER() OVER(PARTITION BY series_id ORDER BY season_id DESC, episode_id DESC) RowNum, * FROM @SeriesInfo;
(样本数据过多见谅)
关键是,如果我们只取 series_id 和 season_id 的最大值,我们将不会得到任何一个系列的有效配对。在这两种情况下,第 1 季的剧集都比第 2 季多。ROW_NUMBER() 子句将每行返回一个唯一编号,但由于“PARTITION BY”,它将为每个 series_id 重新启动(参见注释掉的行)。如果我们只返回 ROW_NUMBER 为 1 的行,我们将得到每个 series_id 的一行,它将是 max season_id 中具有最大 episode_id 的行。
尝试这个..
SELECT * FROM TABLE
HAVING MAX(season_id) AND MAX(episode_id)
GROUP BY series_id
:)
SELECT *
FROM TableName t1
WHERE EXISTS (
SELECT 1
FROM t2
WHERE t1.series_id = t2.series_id
HAVING MAX(t2.season_id) = t1.season_id
AND MAX(t2.episode_id ) = t1.episode_id
)