I have a table such as this
id color shade date
--- ---- ----- -----
1 red dark 01/01/1990
2 red light 09/16/2013
3 green light 08/15/2010
4 green dark 09/18/2012
5 maroon dark 08/20/2013
6 white dark 08/31/2013
7 white light 08/30/2012
8 purple light 08/20/2010
I wanted entries for each color with the latest date. So I tried doing:
select id, color, shade, max(date) from mytable;
This didn't work and gave me error:
is invalid in the select list because it is not contained in either an aggregate
function or the GROUP BY clause.
Alright, so I added it in the Group By
as suggested by the error
select id, color, shade, max(date) from mutable
Group by id, color, shade
This gave me the desired results.
Question
Now, I wanted the same query as above repeated only for certain colors. For example I only wanted to see red and green ones.
So I did:
select id, color, shade, max(date) from mutable
Where color in ('red', 'green')
Group by id, color, shade;
However, this does not give me the correct number of results because I guess they are being grouped by shade
.
What is the best way to fetch my desired results? Basically I want max date
out of the two instances of same thing and further out of the table only want certain colors.
The easiest way to do this is with window/ranking functions. Here is an example with
row_number()
:A simple way to think about this is by first creating a query that gives you the latest date for each colour:
Then by joining this query with a simple select query that just retrieves all rows from your original table:
Then, to restrict the results to only certain colours, just add on your
where
clause at the end of the query:In standard SQL any of the following queries solve the issue:
Option 1
Option 2
In your example data, all the result should be returned, so it doesn't make much sense to operate on it. I've slightly changed it into this:
The output of the queries would be:
Make sure you apply the appropriate orderings.
Fiddle here.
Try this
OUTPUT
OR
OUTPUT
OR
OUTPUT
OVER CLAUSE used IN analyze functions