1

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 Answers2

2

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)
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
Krulwich
  • 41
  • 9
  • This won't give the `cost` column like OP asked, but you can then join this table back with the original table to add the cost. – DarkHark Feb 15 '23 at 00:34
0

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
Fahmi
  • 37,315
  • 5
  • 22
  • 31