我有两张桌子:
CREATE TABLE Students
(
Id int NOT NULL IDENTITY (1,1),
FirstName nvarchar(50) NOT NULL,
LastName nvarchar(50) NOT NULL,
BirthDate datetime NOT NULL,
IndexNumber nvarchar(20) NOT NULL,
ParentName nvarchar(50) NULL,
Gender char(1) NULL,
CONSTRAINT PK_Students PRIMARY KEY (Id)
)
CREATE TABLE StudentComments
(
Id int NOT NULL IDENTITY (1,1),
Comment text NOT NULL,
StudentId int NOT NULL,
InsertAt datetime NOT NULL,
IsPublished bit NOT NULL,
CONSTRAINT PK_StudentComments PRIMARY KEY (Id),
CONSTRAINT FK_StudentComments_Students FOREIGN KEY (StudentId) REFERENCES Students (Id)
)
我的任务是选择Students.Id,Students.FirstName,Students.LastName,StudentComments.Comment,StudentComments.InsertAt,以获取每个学生的最新发表评论。
我需要通过只使用一个select命令(而不是嵌套查询)来完成此操作。
我的尝试查询:
SELECT s.Id,
(s.FirstName + ' ' + s.LastName) AS Name,
sc.Comment,
sc.InsertAt,
MAX(sc.InsertAt) AS NewestDate
FROM Students AS s
INNER JOIN StudentComments sc
ON s.Id = sc.StudentsId AND sc.IsPublished = 1
GROUP BY /* Here is problem - I'm Begginer */
HAVING sc.InsertAt = MAX(scInsertAt);
答案 0 :(得分:0)
尝试以下解决方案之一:
SELECT src.Id, src.FirstName, src.LastName, src.Comment, src.InsertAt
FROM
(
SELECT s.Id, s.FirstName, s.LastName, sc.Comment, sc.InsertAt,
ROW_NUMBER() OVER(PARTITION BY sc.StudentId ORDER BY sc.InsertAt DESC) RowNum
FROM dbo.Students s INNER JOIN dbo.StudentComments sc ON s.Id = sc.StudentId
--WHERE sc.IsPublished = 1
) src
WHERE src.RowNum = 1;
或
SELECT s.Id, s.FirstName, s.LastName, lc.Comment, lc.InsertAt
FROM dbo.Students s
CROSS APPLY (
SELECT TOP(1) sc.Comment, sc.InsertAt
FROM dbo.StudentComments sc
WHERE s.Id = sc.StudentId
--AND sc.IsPublished = 1
ORDER BY sc.InsertAt DESC
) lc; -- Last comment
答案 1 :(得分:0)
你需要一个子查询:
SELECT Students.Id, Students.FirstName, Students.LastName,
(SELECT TOP 1 Comment from StudentComments WHERE StudentID = Students.ID ORDER BY InsertAt DESC) as Comment,
(SELECT TOP 1 InsertAt from StudentComments WHERE StudentID = Students.ID ORDER BY InsertAt DESC) as InsertAt
FROM Students