I have this SQL query:
select date_trunc('month',created_at-'6d 18:06:56'::interval)
+'6d 18:06:56'::interval as created_at,
count(*)filter(where status='ACTIVE') as active,
count(*)filter(where status='BLOCKED') as blocked
from companies
where now()-'12 months'::interval < created_at
group by 1 order by 1;
I tried to use it into Spring Data JPA repository like this:
@Query(value = """
select date_trunc('month',created_at-'6d 18:06:56'::interval)
+'6d 18:06:56'::interval as created_at,
count(*)filter(where status='ACTIVE') as active,
count(*)filter(where status='BLOCKED') as blocked
from companies
where now()- :months + ' months'::interval < created_at
group by 1 order by 1"""
, nativeQuery = true)
List<Result> companiesMonths(@Param("months") Integer months);
But I get error:
SQL Error: 0, SQLState: 42601
ERROR: syntax error at or near ":"
What is the proper way to implement this?
2
Answers
Seems erreur is near
::interval
keyword usage try this:and
months
definition should be like:Inspired by this post: Postgres Interval not working with native spring data JPA query
If Spring doesn’t like the colons, you can get rid of them entirely: demo
Even the literal can use
h
,m
ands
instead of colon-separated time format. That’s all equivalent cast syntax in PostgreSQL:cast('6d 18h06m56s' as interval)
'6d 18h06m56s'::interval
interval '6d 18h06m56s'