【问题标题】:How to remove duplicates in one column and select the first top one only如何删除一列中的重复项并仅选择第一个顶部
【发布时间】:2017-08-11 06:51:13
【问题描述】:
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”的第一行。我尝试使用“按课程名称分组”和“按分区”但不起作用。任何帮助将不胜感激。

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

【问题讨论】:

  • 你真的需要这个群吗?
  • 嗨,实际上是的。我只需要一行具有唯一的“课程代码”。但是现在我得到了多个具有相同“课程代码”的不同行。
  • 为什么要有工会?
  • 这不是 group by 的工作方式。您需要在 group by 子句或聚合函数(如 sum、count、avg 等)中包含选择列表中的每一列
  • @Zohar Peled 你能建议我应该怎么做吗

标签: sql sql-server


【解决方案1】:
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

【讨论】:

  • 感谢您的回答。但我收到以下错误“'partiton' 附近的语法不正确。't' 附近的语法不正确。”
  • 将分区更改为分区
  • @Vecchiasignora 很抱歉,这很尴尬.. 是的,它现在可以工作了.. 请给我几分钟时间用数据对其进行全面测试..
  • 是的,它正在工作!非常感谢...不幸的是,我仍然无法投票给您,因为我仍然是新成员...再次感谢您
猜你喜欢
  • 1970-01-01
  • 2020-03-16
  • 2016-06-04
  • 2014-11-26
  • 1970-01-01
  • 2021-12-20
  • 2018-12-29
  • 2019-08-19
  • 1970-01-01
相关资源
最近更新 更多