SQL - How to select the latest date of every month?

1.2k views Asked by At

I have data set that looks something like this:

|---------------------|------------------|------------------|
|          ID         |        Date      |       Cost       |
|---------------------|------------------|------------------|
|          1          |       9/15/20    |       $500       |
|---------------------|------------------|------------------|
|          1          |       9/30/20    |       $600       |
|---------------------|------------------|------------------|
|          1          |       10/2/20    |       $400       |
|---------------------|------------------|------------------|
|          2          |       10/10/20   |       $1,000     |
|---------------------|------------------|------------------|
|          3          |       9/29/20    |       $600       |
|---------------------|------------------|------------------|
|          3          |       10/5/20    |       $400       |
|---------------------|------------------|------------------|
|          3          |       10/6/20    |       $800       |
|---------------------|------------------|------------------|
|          3          |       10/10/20   |       $200       |
|---------------------|------------------|------------------|

Using SQL Runner in Looker, I want to keep only the rows of the latest date available in each month for each ID. So my example table should end up like this:

|---------------------|------------------|------------------|
|          ID         |        Date      |       Cost       |
|---------------------|------------------|------------------|
|          1          |       9/30/20    |       $600       |
|---------------------|------------------|------------------|
|          1          |       10/2/20    |       $400       |
|---------------------|------------------|------------------|
|          2          |       10/10/20   |       $1,000     |
|---------------------|------------------|------------------|
|          3          |       9/29/20    |       $600       |
|---------------------|------------------|------------------|
|          3          |       10/10/20   |       $200       |
|---------------------|------------------|------------------|
2

There are 2 answers

1
Fahmi On

You can use row_number() if your DBMS supports it

select id, date, cost from
(
  select id, date, cost,
         row_number() over(partition by id order by date desc) as rn
from tablename
)A where rn<=2
1
Krulwich On

The following should run on just about any database:

select id, month(date), max(date) as latest_date_in_month
from <TABLE>
group by id, month(date)
order by id, month(date)