Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select distinct in SQl Server 2008 but for only one field out of many?

Tags:

sql-server

I have a query:

SELECT Content.content_name, Language2.Name, Language2.language_id, 
Content.id, Content.content_description, 
FROM Language AS Language2 
LEFT JOIN contents AS Content ON (Language2.language_id = Content.language_id) 

How do I select only the distinct content_name?

like image 843
bakerjr Avatar asked Apr 27 '10 11:04

bakerjr


People also ask

How do I add distinct to a single column in SQL?

Adding the DISTINCT keyword to a SELECT query causes it to return only unique values for the specified column list so that duplicate rows are removed from the result set. Since DISTINCT operates on all of the fields in SELECT's column list, it can't be applied to an individual field that are part of a larger group.

How do I select a record without duplicates in one column in SQL?

If you want the query to return only unique rows, use the keyword DISTINCT after SELECT . DISTINCT can be used to fetch unique rows from one or more columns. You need to list the columns after the DISTINCT keyword.

Does distinct apply to multiple columns?

Yes, DISTINCT works on all combinations of column values for all columns in the SELECT clause.

How can I get distinct values from multiple columns in SQL?

Select with distinct on all columns of the first query. Select with distinct on multiple columns and order by clause. Count() function and select with distinct on multiple columns.


1 Answers

You do this:

SELECT DISTINCT Content.content_name
FROM Language AS Language2 
LEFT JOIN contents AS Content ON (Language2.language_id = Content.language_id)

So why does this not answer your question?

Let's consider the following data (just the first two columns):

content_name      Name
 XXXXX            1234
 XXXXX            5678

SELECT DISTINCT implies you only want one row, but what do you want for Name?

What you need to do is rewrite the code to use GROUP BY and pick the appropriate aggregate function for the other columns:

SELECT
    Content.content_name,
    MIN(Language2.Name) AS Name,
    MIN(Language2.language_id) AS language_id, 
    MIN(Content.id) AS id,
    MIN(Content.content_description) AS content_description, 
FROM
    Language AS Language2 
    LEFT JOIN contents AS Content
        ON (Language2.language_id = Content.language_id) 
GROUP BY
    Content.content_name

Now, likely this does not produce what you want either, but one thing is for certain, you can not trick the database engine to just "pick one of the rows to return, I don't care which one."

like image 179
Lasse V. Karlsen Avatar answered Nov 16 '22 00:11

Lasse V. Karlsen