我有两张桌子

名字

id | name
---------
5  | bill
15 | bob
10 | nancy


参赛作品

id | name_id | added    | description
----------------------------------
2  | 5       | 20140908 | i added this
4  | 5       | 20140910 | added later on
9  | 10      | 20140908 | i also added this
1  | 15      | 20140805 | added early on
6  | 5       | 20141015 | late to the party


我想按Names表中数值最低的added值中的第一个对Entries进行排序,并显示按added列总体排序的两个表中的行,因此结果将是喜欢:

names.id | names.name | entries.added | entries.description
-----------------------------------------------------------
15       | bob        | 20140805      | added early on
5        | bill       | 20140908      | i added this
10       | nancy      | 20140908      | i also added this


我研究了第一个项目的联接(例如SQL Server: How to Join to first row),但无法使其正常工作。

有小费吗?

最佳答案

应该这样做:

SELECT n.id, n.name, e.added, e.description
FROM Names n INNER JOIN
     (SELECT name_id, description, Min(added) FROM Entries GROUP BY name_id, description) e
     ON n.id = e.name_id
ORDER BY e.added

10-05 22:51