Search code examples
jpaeclipselinkquerydsl

SELECT distinct field in Querydsl


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.


Solution

  • 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());