0

I have a table with columns of names 'Name', 'Product', 'Value', 'Update Date'. I want to have an SQL statement that selects the unique values of the columns 'Name', 'Product', 'Value' but do so in a way that they are ordered by most recent to least recent 'Update Date.'

If I return the output of such an SQL select statement, I could easily get, let's say the three Names or the three Products, three Values, that had the most recent updates. Is there an SQL statement I could use?

I am thinking about having a separate SQL statement for each of the columns: 'Name', 'Product', 'Value'. And have an ORDER BY statement somewhere. Any thoughts?

Diana Vazquez Romo
  • 152
  • 1
  • 1
  • 11
  • **[edit]** your question and add some sample data and the expected output based on that data. [**Formatted text**](http://stackoverflow.com/help/formatting) please, [no screen shots](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557). Do not post code or additional information in comments –  Jul 20 '17 at 20:33
  • Which [DBMS](https://en.wikipedia.org/wiki/Database) are you using? Postgres? Oracle? DB2? Firebird? –  Jul 20 '17 at 20:33

1 Answers1

2

You need to switch to an aggregate to get the maximum date for sorting:

select Name, Product, Value
from tab
group by Name, Product, Value
order by MAX(UpdateDate) desc
dnoeth
  • 59,503
  • 4
  • 39
  • 56
  • Thank you!! Just to clarify, this query would get the unique entries consisting of columns Name, Product, Value, that have the largest UpdateDate. If I would like the unique entry to consist not of the three columns, Name, Product, Value but rather Name alone or Product alone or Value alone, I would need to execute separate statements right? As in: select Name from tab group by Name order by MAX(UpdateDate) desc, select Product from tab group by Product order by MAX(UpdateDate) desc, .... etc. – Diana Vazquez Romo Jul 21 '17 at 09:02
  • 1
    @Diana: Yep, it returns the unique `Name, Product, Value` *combinations* and sorts by the latest `UpdateDate`. If you want to to that for each single column you will need three Select plus `UNION ALL`. – dnoeth Jul 21 '17 at 09:05