我对SQL很天真...请帮我解决下面的问题:
我有一个名为Course
的表,如下所示:
Key CourseName CourseId IsCurrentVersion
0 Course_1 A 0
1 Course_1 A 0
2 Course_1 A 1
3 Course_2 B 0
4 Course_2 B 0
5 Course_3 C 1
6 Course_4 D 0
7 Course_5 E 0
8 Course_5 E 0
9 Course_6 F 1
10 Course_6 F 1
11 Course_6 F 1
12 Course_7 G 1
13 Course_7 G 0
14 Course_7 G 0
我想要以下结果集:
CourseName CourseId IsCurrentVersion
Course_1 A 1
Course_2 B 0
Course_3 C 1
Course_4 D 0
Course_5 E 0
Course_6 F 1
Course_7 G 1
对于具有相同CourseId的记录;具有1的IsCurrentVersion应该优先于0.单个记录也应该在输出中显示,而不管它们的IsCurrentVersion值。
数据库是SQL Server 2008。
答案 0 :(得分:0)
假设IsCurrentVersion的唯一值为1和0,这应该可以满足您的需求。
SELECT CourseName, CourseId, MAX(IsCurrentVersion)
FROM Course
GROUP BY CourseName, CourseID
如果IsCurrentVersion列是一个位而不是整数,请改用它。
SELECT CourseName, CourseId, MAX(CASE WHEN IsCurrentVersion = 1 THEN 1 ELSE 0 END)
FROM Course
GROUP BY CourseName, CourseID
答案 1 :(得分:0)
试试这个:
SELECT CourseName, CourseId, IsCurrentVersion
FROM Course AS A
WHERE IsCurrentVersion = (SELECT MAX(IsCurrentVersion)
FROM Course AS B
WHERE A.CourseId = B.CourseId)
GROUP BY CourseName, CourseID, IsCurrentVersion