I have a table which have three fields ID,Name,aDate. I want result on distinct name and i want date to be in result. I am using query as
Select distinct(Name),adate from table_name.
But i am getting wrong results.i think sql is appling distinct on combination of both fields. What i do help me. I want distinct name values with their respective adate field.
If you only want ONE Date per Name then you have to specify which date:
Eg:
SELECT Name, Max(aDate)
FROM table_name
GROUP BY Name
Since this statement uses GROUP BY Name
it will only return one row for each Name. Since it uses an aggregation of aDate (in my example the MAX()
function) it will return the appropriate date which you want.
In general you should try to avoid the use of the DISTINCT keyword. It is seldom the right approach.
If you simply want the list of distinct names used in your table you can use
SELECT DISTINCT Name
FROM table_name
which will return the same results as
SELECT Name
FROM table_name
GROUP BY Name
Distinct does not work on one field it works across the whole row of fields in query. So what you are asking does not make sense.
If your table has rows like this
|ID|Name|Date|
|1|John|2011-4-1|
|2|John|2011-4-2|
|3|John|2011-4-2|
then when you call Select distinct name, date
what are you expecting to see in the date column?
you need to decide which date.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.