3

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 I use the distinct function, It returns all of the distinct rows so...

select distinct teacher from class etc.

This works fine, but I am selecting multiple columns, so...

select distinct teacher, student etc.

but I don't want to retrieve the distinct rows, I want the distinct rows where the teacher is distinct. So this query would probably return the same teacher's name multiple times because the student value is different but what I would like is to return rows where the teachers are distinct, even if it means returning the teacher and one student name (because I don't need all the students).

I hope what I am trying to ask is clear but is it possible to use the distinct function on a single column even when selecting multiple columns or is there any other solution to this problem? Thanks.


The above is just an example I am giving. I don't know if using 'distinct' is the solution to my problem. I am not using teacher etc. that was just an example to get the idea accross. I am selecting multiple columns (about 10) from different tables. I have a query to get the tabled result I want. Now I want to query that table to find the unique values in one particular column. So using the teacher example again, say I have wrote a query and I have all the teachers and all the pupils they teach. Now I want to go through each row in this table and email the teacher a message. But I don't want to email the teacher numerous times, just the once, so I want to return all the columns from the table I have, where only the teacher value is distinct.

Col A Col B Col C Col D

a b c d

a c d b

b a a c

b c c c

A query I have produces the above table. Now I want only those rows where Col A values are unique. How would I go about it?

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
  • 3
    Why do you need a student name in there at all? Even if you can do it, what use is a random student name out of many? – JimG Jul 22 '09 at 10:59
  • As many people, I don't understand your question I think. What do you want your query to return ? The list of teachers, distinct ? The list of teacher, distinct, and how much student they have ? The list of teachers, distinct, and a random student ? the last student ? Be more accurate please – Clement Herreman Jul 22 '09 at 11:35
  • which row do you want where col A values are unique. 'a b c d' or 'a c d b' – Matthew Vines Jul 22 '09 at 13:56
  • Either one. It is not important which row is retrieved because all I want from the row is say.. the teachers email address and if both rows that you mentioned have the same teacher then any one will do because they both have the correct email address(assuming col a was the teachers name column). –  Jul 22 '09 at 13:59
  • If it doesn't matter what the other columns are why return them in your result set. Just select from column 1 and apply the distinct keyword. – Matthew Vines Jul 22 '09 at 14:02
  • To the original poster: do you mean you want the distinct list of teachers and *just don't care* which student is returned in that column? – Jeff Sternal Jul 22 '09 at 14:43
  • @Please don't post exact duplicate questions. I merged two **exact** duplicates and cleaned up the comments. – Bill the Lizard Jul 22 '09 at 16:31

18 Answers18

11

You have misunderstood the DISTINCT keyword. It is not a function and it does not modify a column. You cannot SELECT a, DISTINCT(b), c, DISTINCT(d) FROM SomeTable. DISTINCT is a modifier for the query itself, i.e. you don't select a distinct column, you make a SELECT DISTINCT query.

In other words: DISTINCT tells the server to go through the whole result set and remove all duplicate rows after the query has been performed.

If you need a column to contain every value once, you need to GROUP BY that column. Once you do that, the server now needs to do which student to select with each teacher, if there are multiple, so you need to provide a so-called aggregate function like COUNT(). Example:

SELECT teacher, COUNT(student) AS amountStudents
FROM ...
GROUP BY teacher;
soulmerge
  • 73,842
  • 19
  • 118
  • 155
2

One option is to use a GROUP BY on Col A. Example:

SELECT * FROM table_name GROUP BY Col A

That should return you:

abcd

baac

dmertl
  • 805
  • 8
  • 13
  • 2
    Depending on the DB server being used, this is not necessarily true. If he is using MSSQL this query would result in an error like the following: "Column 'B' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause." – Chris Porter Jul 22 '09 at 14:35
2

I'm not sure if I am understanding this right but couldn't you do

SELECT * FROM class WHERE teacher IN (SELECT DISTINCT teacher FROM class)

This would return all of the data in each row where the teacher is distinct

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Mentee
  • 51
  • 2
2

Based on the limited details you provided in your question (you should explain how/why your data is in different tables, what DB server you are using, etc) you can approach this from 2 different directions.

  1. Reduce the number of columns in your query to only return the "teacher" and "email" columns but using the existing WHERE criteria. The problem you have with your current attempt is both DISTINCT and GROUP BY don't understand that you one want 1 row for each value of the column that you are trying to be distinct about. From what I understand, MySQL has support for what you are doing using GROUP BY but MSSQL does not support result columns not included in the GROUP BY statement. If you don't need the "student" columns, don't put them in your result set.

  2. Convert your existing query to use column based sub-queries so that you only return a single result for non-grouped data.

Example:

SELECT t1.a
        , (SELECT TOP 1 b FROM Table1 t2 WHERE t1.a = t2.a) AS b
        , (SELECT TOP 1 c FROM Table1 t2 WHERE t1.a = t2.a) AS c
        , (SELECT TOP 1 d FROM Table1 t2 WHERE t1.a = t2.a) AS d
    FROM dbo.Table1 t1
    WHERE (your criteria here)
    GROUP BY t1.a

This query will not be fast if you have a lot of data, but it will return a single row per teacher with a somewhat random value for the remaining columns. You can also add an ORDER BY to each sub-query to further tweak the values returned for the additional columns.

Chris Porter
  • 3,627
  • 25
  • 28
1

distinct requires a unique result-set row. This means that whatever values you select from your table will need to be distinct together as a row from any other row in the result-set.

Using distinct can return the same value more than once from a given field as long as the other corresponding fields in the row are distinct as well.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
1

As soulmerge and Shiraz have mentioned you'll need to use a GROUP BY and subselect. This worked for me.

DECLARE @table TABLE (
    [Teacher] [NVarchar](256) NOT NULL ,
    [Student] [NVarchar](256) NOT NULL 
)

INSERT INTO @table VALUES ('Teacher 1', 'Student 1')
INSERT INTO @table VALUES ('Teacher 1', 'Student 2')
INSERT INTO @table VALUES ('Teacher 2', 'Student 3')
INSERT INTO @table VALUES ('Teacher 2', 'Student 4')

SELECT 
    T.[Teacher],  
    (
        SELECT TOP 1 T2.[Student]
        FROM @table AS T2 
        WHERE T2.[Teacher] = T.[Teacher]
    ) AS [Student]
FROM @table AS T
GROUP BY T.[Teacher]

Results

Teacher 1, Student 1
Teacher 2, Student 3
Kane
  • 16,471
  • 11
  • 61
  • 86
0

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

Shiraz Bhaiji
  • 64,065
  • 34
  • 143
  • 252
0

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

Kuroki Kaze
  • 8,161
  • 4
  • 36
  • 48
0

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?

dnagirl
  • 20,196
  • 13
  • 80
  • 123
0

You will need to say how your data is stored in-memory for us to say how you can query it.

But you could do a separate query to just get the distinct teachers.

select distinct teacher from class
Matt Howells
  • 40,310
  • 20
  • 83
  • 102
  • But I would need the distinct teachers from the results of the other query, not all teachers –  Jul 22 '09 at 14:02
0

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.

Dave Morgan
  • 1,055
  • 1
  • 13
  • 19
0

You could use GROUP BY to separate the return values based on a single column value.

sangretu
  • 1,208
  • 9
  • 12
0

All you have to do is select just the columns you want the first one and do a select Distinct

Select Distinct column1 -- where your criteria...
Matthew Vines
  • 27,253
  • 7
  • 76
  • 97
0
select cola,colb,colc 
from yourtable
where cola in 
(
  select cola from yourtable where your criteria group by cola having count(*) = 1
)
aquinas
  • 23,318
  • 5
  • 58
  • 81
  • This query will still return every row in the table that matches your where criteria. The distinct statement in the sub-query has no real value. – Chris Porter Jul 22 '09 at 14:31
  • Whoops. :) Edited. Although frankly, I'm still not sure I even understand what the question is asking for. – aquinas Jul 22 '09 at 15:02
0

The following might help you get to your solution. The other poster did point to this but his syntax for group by was incorrect.

Get all teachers that teach any classes.

   Select teacher_id, count(*)
    from teacher_table inner join classes_table
    on teacher_table.teacher_id = classes_table.teacher_id
    group by teacher_id
blispr
  • 883
  • 5
  • 10
0

Noone seems to understand what you want. I will take another guess.

Select * from tbl
Where ColA in (Select ColA from tbl Group by ColA Having Count(ColA) = 1)

This will return all data from rows where ColA is unique -i.e. there isn't another row with the same ColA value. Of course, that means zero rows from the sample data you provided.

Bill
  • 4,425
  • 3
  • 21
  • 22
0
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.

kri
  • 494
  • 1
  • 6
  • 12
0
CREATE FUNCTION dbo.DistinctList
(
@List VARCHAR(MAX),
@Delim CHAR
)
RETURNS
VARCHAR(MAX)
AS
BEGIN
DECLARE @ParsedList TABLE
(
Item VARCHAR(MAX)
)
DECLARE @list1 VARCHAR(MAX), @Pos INT, @rList VARCHAR(MAX)
SET @list = LTRIM(RTRIM(@list)) + @Delim
SET @pos = CHARINDEX(@delim, @list, 1)
WHILE @pos > 0
BEGIN
SET @list1 = LTRIM(RTRIM(LEFT(@list, @pos - 1)))
IF @list1 <> ''
INSERT INTO @ParsedList VALUES (CAST(@list1 AS VARCHAR(MAX)))
SET @list = SUBSTRING(@list, @pos+1, LEN(@list))
SET @pos = CHARINDEX(@delim, @list, 1)
END
SELECT @rlist = COALESCE(@rlist+',','') + item
FROM (SELECT DISTINCT Item FROM @ParsedList) t
RETURN @rlist
END
GO
user0042
  • 7,917
  • 3
  • 24
  • 39