-1

I have a column which contain dates of transactions occurred on working days. I am trying to group my customers to see their end of month totals for the last number of months.

Essentially, how do I get the max date for each of the last 6 months in SQL?

Example table below

ID Date
610 11/30/2021
610 11/29/2021
610 11/28/2021
610 10/29/2021
610 10/15/2021
610 9/15/2021
610 9/14/2021
610 8/10/2021
725 11/30/2021
725 11/29/2021
725 11/28/2021
725 10/29/2021
725 10/15/2021
725 9/15/2021
725 9/14/2021
725 8/10/2021

what I would like to return is the table below

ID Date
610 11/30/2021
610 10/15/2021
610 9/15/2021
610 8/10/2021
725 11/30/2021
725 10/29/2021
725 9/15/2021
725 8/10/2021
Motacular
  • 33
  • 7

2 Answers2

0

Aggregate and group by the YEAR and MONTH of your date column in a subquery to get the MAX date per month (and year), then do not return the year and month in the outer query.

divisionby0
  • 170
  • 5
0

I have assumed the table name as Test and first column as Code and Second column name as TransactionDate. I have implemented my query in SQL SERVER.

SELECT Code, FORMAT (Max(TransactionDate), 'dd/MM/yyyy ') 
FROM Test
GROUP By Code, MONTH(TransactionDate), YEAR(TransactionDate)
ORDER By Code ASC, Max(TransactionDate) DESC

You can check my query in SQL Fiddle. Link