I guess it is really hard to be friends with sql. Please help!
I have history table that contains master records of customer for 3 years.
the table looks like this:
Table A:
| ID | Name | Number|Date(in Timestamp)|
|:--- |:----:|:-----:|-----------------:|
|123 | John | 101 |20210101 01:11:15 |
|123 | John | 102 |20210103 01:11:15 |
|123 | John | 103 |20210301 01:11:15 |
|123 | John | 104 |20210325 01:11:15 |
|123 | John | 105 |20210415 01:11:15 |
|123 | John | 106 |20210416 01:11:15 |
|124 | Mary | 201 |20210101 01:11:15 |
|124 | Mary | 202 |20210103 01:11:15 |
|124 | Mary | 203 |20210201 01:11:15 |
|124 | Mary | 204 |20210225 01:11:15 |
|124 | Mary | 204 |20210315 01:11:15 |
|124 | Mary | 205 |20210416 01:11:15 |
I need to know what are the records of each customers at the end of each month.
Expected result is:
| ID | Name | Number|Date |
|123 | John | 102 |20210131|
|123 | John | 104 |20210331|
|123 | John | 106 |20210430|
|124 | Mary | 202 |20210131|
|124 | Mary | 204 |20210228|
|124 | Mary | 204 |20210331|
|124 | Mary | 205 |20210430|
I created below sql but it looks like i cannot use substr for Timestamp. Is there any other way to do this? will really appreciate any help!
select * from (select t1.id, t1.name, t1.number, t1.date,
ROW_NUMBER() over (partition by substr(date,1,6) order by date desc) as Rowrank
from tableA t1)sub where Rowrank = 1