如何删除一列中的重复项并仅选择第一个顶层副本

时间:2017-03-20 04:49:42

标签: sql sql-server

select * from 
(select M.* from zstatistics M JOIN ZEntrycriteria C ON  M.coursecode=C.Course_code 
    where C.Maths <= @maths 
    AND C.Science <= @science 
    AND C.English <= @english 
    And C.Ict <= @ict 
    And C.History <= @history 
    And C.Geography <= @geography 
    And C.Art <= @Art 
UNION 
    select M.* from zsuggestions M JOIN ZEntrycriteria C ON M.coursecode=C.Course_code 
    where C.Maths <= @maths 
    AND C.Science <= @science 
    AND C.English <= @english 
    And C.Ict <= @ict 
    And C.History <= @history 
    And C.Geography <= @geography 
    And C.Art <= @Art 

)t

ORDER BY sqrt( power(t.Maths - @maths, 2) + power(t.Science - @science,2) + power(t.English - @english,2) + power(t.Ict - @ict,2) + power(t.History-@history,2) + power(t.Geography - @geography,2) + power(t.Art - @Art,2))

上面的sql查询给出了以下答案。

SchoolName| CourseName| Maths| Science| English| History|Geography|Art|ICT

xyz       |  abcd     |45    |85      |85      |  95    |58       |65 |85

xyz       |  abcd     |85    |95      | 68     |80      |  100    |40 |80

kkk       |  ku       |60    |50      | 54     | 82     |82       |58 |95

.
.
.

正如您所看到的,CourseName列有两个带有不同数据的“abcd”。我的问题是我如何只获得“abcd”的第一行。我试过“group by CourseName”和“Partition by”但是没有用。任何帮助将不胜感激。

我想我找到了答案here!但我不明白如何在我的场景中使用它(抱歉英语不好)

1 个答案:

答案 0 :(得分:2)

try this

select * from (select ROW_NUMBER() over (partition by CourseName order by  sqrt( power(t.Maths - @maths, 2) + power(t.Science - @science,2) + power(t.English - @english,2) + power(t.Ict - @ict,2) + power(t.History-@history,2) + power(t.Geography - @geography,2) + power(t.Art - @Art,2)) ) rownumb , t.* from 
(select M.* from zstatistics M JOIN ZEntrycriteria C ON  M.coursecode=C.Course_code 
    where C.Maths <= @maths 
    AND C.Science <= @science 
    AND C.English <= @english 
    And C.Ict <= @ict 
    And C.History <= @history 
    And C.Geography <= @geography 
    And C.Art <= @Art 
UNION 
    select M.* from zsuggestions M JOIN ZEntrycriteria C ON M.coursecode=C.Course_code 
    where C.Maths <= @maths 
    AND C.Science <= @science 
    AND C.English <= @english 
    And C.Ict <= @ict 
    And C.History <= @history 
    And C.Geography <= @geography 
    And C.Art <= @Art 
) t) a
where  a.rownumb=1