Using the distinct function in SQL

前端 未结 18 946
無奈伤痛
無奈伤痛 2021-02-06 16:55

I have a SQL query I am running. What I was wanting to know is that is there a way of selecting the rows in a table where the value in on one of those columns is distinct? When

相关标签:
18条回答
  • 2021-02-06 17:35

    You need to do it with a sub select where you take TOP 1 of student where the teacher is the same.

    0 讨论(0)
  • 2021-02-06 17:37
    declare @temp as table (colA nchar, colB nchar, colC nchar, colD nchar, rownum int)
    
    insert @temp (colA, colB, colC, colD, rownum)
    select Test.ColA, Test.ColB, Test.ColC, Test.ColD, ROW_NUMBER() over (order by ColA) as rownum
        from Test
    
    select t1.ColA, ColB, ColC, ColD
    from @temp as t1
    join (
        select ColA, MIN(rownum) [min]
        from @temp
        group by Cola)
     as t2 on t1.Cola = t2.Cola and t1.rownum = t2.[min]
    

    This will return a single row for each value of the colA.

    0 讨论(0)
  • 2021-02-06 17:40

    You may try "GROUP BY teacher" to return what you need.

    0 讨论(0)
  • 2021-02-06 17:42

    What is the question your query is trying to answer?

    Do you need to know which classes have only one teacher?

    select class_name, count(teacher) 
    from class group by class_name having count(teacher)=1
    

    Or are you looking for teachers with only one student?

    select teacher, count(student) 
    from class group by teacher having count(student)=1
    

    Or is it something else? The question you've posed assumes that using DISTINCT is the correct approach to the query you're trying to construct. It seems likely this is not the case. Could you describe the question you're trying to answer with DISTINCT?

    0 讨论(0)
  • 2021-02-06 17:44
    select cola,colb,colc 
    from yourtable
    where cola in 
    (
      select cola from yourtable where your criteria group by cola having count(*) = 1
    )
    
    0 讨论(0)
  • 2021-02-06 17:45

    I am struggling to understand exactly what you wish to do.. but you can do something like this:

    SELECT DISTINCT ColA FROM Table WHERE ...
    

    If you only select a singular column, the distinct will only grab those.

    If you could clarify a little more, I could try to help a bit more.

    0 讨论(0)
提交回复
热议问题