假设您有以下投影:
Artist Painting Year
---------------------------------------
Alfred Birds 1945
Alfred Apples&Oranges 1947
Ben ZealousNeighbours 1912
Calum Hope Spliced 1760
Calum Horseplay 1765
Calum Earth 1780
David Apples&Oranges 1947
如何返回以下第一个关系:
Artist Painting Year
---------------------------------------
Alfred Birds 1945
Ben ZealousNeighbours 1912
Calum Hope Spliced 1760
David Apples&Oranges 1947
即每位画家画的第一幅画......
仅限ANSI SQL
答案 0 :(得分:1)
尝试以下方法:
SELECT
[Artist],
[Painting],
[Year]
FROM
(
SELECT
[Artist],
[Painting],
[Year],
ROW_NUMBER() OVER(PARTITION BY [Artist] ORDER BY [Year] ASC) AS [Rank]
FROM
[Table]
) AS a
WHERE
a.[Rank] = 1
答案 1 :(得分:0)
这适用于任何符合ANSI-89标准的SQL方言,但是如果艺术家在第一年内完成了多幅绘画,它就会破坏 - 你可以通过存储一个实际的日期时间值来调整它,如果你需要更精细的粒度,那么就可以调整它
SELECT *
FROM Paintings
INNER JOIN
(SELECT Artist, MIN([Year]) MinYear
FROM Paintings
GROUP BY Artist)
Minimum ON Minimum.MinYear = Paintings.Year AND Minimum.Artist = Paintings.Artist
如果您的SQL符合ANSI-2003标准,您可以执行上面列出的diaho。
e:我认为没有办法确保每位艺术家仅使用ANSI-89 SQL返回一行。