2015-06-03 40 views
1

我天真的SQL ......請幫我下面的查詢:SQL:要獲取單個記錄每個CourseId

我有如下一個名爲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

試試這個:

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 
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 
+0

我收到NULL在CourseId的所有記錄。 – Tarun