I'm trying, as in title, to insert a subquery in select clause like in this simple SQL:
SELECT id, name, (select count(*) from item) from item
this is obviously only a mock query just to make my point. (The point would be to get the last invoice for each item returned by the query.)
I've tried this:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> c = cb.createTupleQuery();
Root<Item> item= c.from(Item.class);
Subquery<Long> scount = c.subquery(Long.class);
Root<Item> sarticolo = scount.from(Item.class);
scount.select(cb.count(sitem));
c.multiselect(item.get("id"),item.get("nome"), scount);
Query q = em.createQuery(c);
q.setMaxResults(100);
List<Tuple> result = q.getResultList();
for(Tuple t: result){
System.out.println(t.get(0) + ", " + t.get(1) + ", " + t.get(2));
}
but I only get:
java.lang.IllegalStateException: Subquery cannot occur in select clause
How can I get a similar result?
SELECT id, creationDate, suspendedDate, type, title, description, (select count(case when i don't follow) from notification) from notification
– Intermediate