You can use window function and Cte to solve the problem
you use FORMAT to find part YYYY MM of date
;WITH _Lstdate AS (
SELECT
SnapshotDate
,NrAccounts
,Status
,AccountType
,RegisteredCountry
,RegisteredCountryID
, Rank() OVER (
PARTITION BY FORMAT (SnapshotDate, 'YYYY-MM')
ORDER BY SnapshotDate desc
) rw
FROM Lstdate
)
SELECT
FORMAT (SnapshotDate, 'yyyy-MM') +'-01' AS SnapshotDate,
NrAccounts,
Status,
AccountType,
RegisteredCountry,
RegisteredCountryID
FROM _Lstdate
WHERE rw = 1
ORDER BY SnapshotDate
You can insert the basic data with the following statements:
drop table if exists Lstdate
create table Lstdate (SnapshotDate date,NrAccounts int,Status varchar(100),RegisteredCountry varchar(100)
,RegisteredCountryId int,AccountType varchar(100))
insert into Lstdate
(SnapshotDate,AccountType,NrAccounts,Status,RegisteredCountry,RegisteredCountryId)
select '2023/01/01' as SnapshotDate ,'BELGIAN_NRN' as AccountType,585 as NrAccounts,'ACTIVATED' as Status,'Belgian' as RegisteredCountry,1 as RegisteredCountryId
union all select '2023/02/01' as SnapshotDate ,'BELGIAN_NRN' as AccountType,585 as NrAccounts,'ACTIVATED' as Status,'Belgian' as RegisteredCountry,1 as RegisteredCountryId
union all select '2023/03/01' as SnapshotDate ,'BELGIAN_NRN' as AccountType,585 as NrAccounts,'ACTIVATED' as Status,'Belgian' as RegisteredCountry,1 as RegisteredCountryId
union all select '2023/03/29' as SnapshotDate ,'BELGIAN_NRN' as AccountType,585 as NrAccounts,'ACTIVATED' as Status,'Belgian' as RegisteredCountry,1 as RegisteredCountryId
union all select '2023/04/11' as SnapshotDate ,'BELGIAN_NRN' as AccountType,7578 as NrAccounts,'ACTIVATED' as Status,'Belgian' as RegisteredCountry,1 as RegisteredCountryId
union all select '2023/04/13' as SnapshotDate ,'BELGIAN_NRN' as AccountType,58 as NrAccounts,'ACTIVATED' as Status,'Belgian' as RegisteredCountry,1 as RegisteredCountryId
union all select '2023/04/14' as SnapshotDate ,'BELGIAN_NRN' as AccountType,58 as NrAccounts,'ACTIVATED' as Status,'Belgian' as RegisteredCountry,1 as RegisteredCountryId
union all select '2023/04/15' as SnapshotDate ,'BELGIAN_NRN' as AccountType,22 as NrAccounts,'ACTIVATED' as Status,'Belgian' as RegisteredCountry,1 as RegisteredCountryId