我有一个包含这些列的表:
id | series_id | season_id | episode_id | title | type ...
我希望获得具有唯一series_id
的行,其中season_id
和episode_id
最多。
答案 0 :(得分:1)
一种解决方案是:
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;
答案 1 :(得分:0)
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
)
答案 2 :(得分:0)
试试这个..
SELECT * FROM TABLE
HAVING MAX(season_id) AND MAX(episode_id)
GROUP BY series_id
:)
答案 3 :(得分:0)
我认为这可能有点矫枉过正,但这是我发现对我有用的唯一方法。
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中具有max episode_id的行。