2

I would like to ask about how to make a SELECT Distinct on field in Querydsl 4. What is the best way to do this SQL request:

SELECT DISTINCT ON 
    (company_id, EXTRACT(MONTH FROM createddt), EXTRACT(YEAR FROM createddt)) id, 
    createddt 
FROM companystats 
ORDER BY company_id, 
    EXTRACT(MONTH FROM createddt) DESC,
    EXTRACT(YEAR FROM createddt) DESC,
    createddt DESC

Thanks.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
Mohamed
  • 113
  • 1
  • 2
  • 7

1 Answers1

5

Your SQL looks like a Postgres-Query. So, the best way would be to use distinctOn in com.querydsl.sql.postgresql.PostgreSQLQuery.

PostgreSQLQuery query = new PostgreSQLQuery(con);
query.select(companystats.id, companystats.createddt)
    .distinctOn(companystats.company_id, 
        companystats.createddt.month(), companystats.createddt.year())
    .from(companystats)
    .orderBy(companystats.createddt.month().desc(), 
             companystats.createddt.year().desc(),
             companystats.createddt.desc());
Meiko Rachimow
  • 4,664
  • 2
  • 25
  • 43