这是我的表
UserDetail
Id UserId CourseId SubjectId TeacherCode RDate status
1 1 1 1 1 08/02/2016 Waiting
2 1 1 1 2 08/01/2016 Recceived
3 1 1 1 3 08/02/2016 Processed
4 1 1 2 1 08/03/2016 Recceived
5 1 1 2 2 08/04/2016 Processed
6 1 2 1 3 08/05/2016 Processed
7 1 2 2 1 08/06/2016 Processed
用户可以有多个课程,多个科目。一个教师可以教多个科目。我想从表格中获取所有栏目,基于不同的用户标识,课程和主题。在7行中,只要显示4行。 下面的任何一条记录
Id UserId CourseId SubjectId TeacherCode RDate status
1 1 1 1 1 08/02/2016 Waiting
2 1 1 1 2 08/01/2016 Recceived
3 1 1 1 3 08/02/2016 Processed
如果我们选择教师代码1,则rdate为08/02/2016并且状态为Waiting 既不接受也不处理。 下面的任何一个
Id UserId CourseId SubjectId TeacherCode RDate status
4 1 1 2 1 08/03/2016 Recceived
5 1 1 2 2 08/04/2016 Processed
怎么做?
答案 0 :(得分:1)
您必须知道要选择哪些区别的数据。第一排?最后一行?
因为每组有区别的数据都是多行,所以你应该选择你想要的那一行。
我假设您想要每个特定组的第一行。你可以这样做:
Select first(Id) AS Id, first(UserId) AS UserId, first(CrouseId) AS CourseId, first(SubjectId) AS SubjectId, first(TeacherId) AS TescherId,first(RDate) AS RDate, first(status) as status
FROM UserDetail
Group By UserId, CourseId, SubjectId
在sql2005 +中,如下所示:
WITH temp AS (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY UserId,CourseId,SubjectId ORDER BY Id) AS rn FROM UserDetail)
SELECT t.*
FROM temp t
WHERE t.rn = 1
或者您可以使用内部选择而不是WITH:
来实现SELECT *
FROM (SELECT *,
ROW_NUMBER() OVER(PARTITION BY UserId,CourseId,SubjectId ORDER BY Id) AS rn FROM UserDetail)
WHERE rn = 1