简体   繁体   中英

Spring Data, JPQL, Group by month of a date column(type LocalDate)

I have to get total price in month from a date yy-mm-dd with jpql query but I can't do it.

@Query(value = "select new com.talan.food.dto.MonthIncomes( function('date_format',date,'%Y-%m'),SUM(p.price)) from Reservation p group by function('date_format',p.date,'%Y-%m')" )

public List<MonthIncomes> getIncomeByMonth();

And in the table of entity I have:

public class Reservation {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private double price;
    @ManyToOne @JoinColumn(name="userId" )
    public User  user;
    private LocalDate date;
    private boolean confirmed;
}

And I will put the result in the class:

public class MonthIncomes {
    private LocalDate date ;
    private double price;

    public MonthIncomes (LocalDate date, double price) {
           this. date=  date;
           this.price = price;
    }
}

You could something like this in your query

SELECT p.date as date , 
SUM(p.price) as price 
FROM reservation p 
WHERE p.date >= '2022-01-01'
GROUP BY
EXTRACT(month from p.date)

depending on the amount of yours you have to go back you would have to change the extract statement a bit. Nevertheless your problem looks like something that you could approach with the extract function

https://www.postgresqltutorial.com/postgresql-date-functions/postgresql-extract/

i resolve the problem by using this syntaxe:

@Query(value = "select new com.food.dto.MonthIncomes(EXTRACT(month from p.date),SUM(p.price)) from Reservation p group by EXTRACT(month from p.date) ORDER BY EXTRACT(month from p.date)")

public List<MonthIncomes> getIncomeByMonth();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM