SELECT DISTINCT field1, field2, field3, ...... FROM table
I am trying to accomplish the following sql statement but I want it to return all columns is this possible? Something like:
SELECT DISTINCT field1, * from table
SELECT DISTINCT field1, field2, field3, ...... FROM table
I am trying to accomplish the following sql statement but I want it to return all columns is this possible? Something like:
SELECT DISTINCT field1, * from table
From the phrasing of your question, I understand that you want to select the distinct values for a given field and for each such value to have all the other column values in the same row listed. Most DBMSs will not allow this with neither
DISTINCT
norGROUP BY
, because the result is not determined.Think of it like this: if your
field1
occurs more than once, what value offield2
will be listed (given that you have the same value forfield1
in two rows but two distinct values offield2
in those two rows).You can however use aggregate functions (explicitely for every field that you want to be shown) and using a
GROUP BY
instead ofDISTINCT
:For SQL Server you can use the dense_rank and additional windowing functions to get all rows AND columns with duplicated values on specified columns. Here is an example...
This is taking a row count for each distinct combination of col1, col2, and col3.
That's a really good question. I have read some useful answers here already, but probably I can add a more precise explanation.
Reducing the number of query results with a GROUP BY statement is easy as long as you don't query additional information. Let's assume you got the following table 'locations'.
Now the query
will result in:
However, the following query
...throws an error in MS SQL, because how could your computer know which of the three French cities "Lyon", "Paris" or "Marseille" you want to read in the field to the right of "France"?
In order to correct the second query, you must add this information. One way to do this is to use the functions MAX() or MIN(), selecting the biggest or smallest value among all candidates. MAX() and MIN() are not only applicable to numeric values, but also compare the alphabetical order of string values.
will result in:
or:
will result in:
These functions are a good solution as long as you are fine with selecting your value from the either ends of the alphabetical (or numeric) order. But what if this is not the case? Let us assume that you need a value with a certain characteristic, e.g. starting with the letter 'M'. Now things get complicated.
The only solution I could find so far is to put your whole query into a subquery, and to construct the additional column outside of it by hands:
will result in: