我有这个实体:
@Entity
public class TDInvestment {
@Id
private String tdName;
@Id
private LocalDate readingDate;
//more attributes
}
知道我有String tdName
和LocalDate readingDate
标识的唯一实体,如何选择所有最新实体(使用Hibernate HQL或本机SQL)?我知道我可以使用... order by readingDate desc;
将最新的行放在最上面,但是如何只选择每个唯一tdName
的最新行?
更新
我尝试使用
select tdName, max(readingDate)
from table
group by tdName;
并且仅当表只有这2列时才有效。如果它有更多非唯一列,我怎样才能使它工作?
实施例(日/月/年):
tdName readingDate unitPrice other non unique Columns
abc 10/02/2018 214125.34 ...
def 25/01/2012 134.21312 ...
abc 21/11/2015 54983.23 ...
def 19/07/2011 0.2374 ...
abc 01/03/2002 83271.1 ...
ghi 11/10/1950 12 ...
我的查询应该返回:
tdName readingDate unitPrice other non unique Columns
abc 10/02/2018 214125.34 ...
def 25/01/2012 134.21312 ...
ghi 11/10/1950 12 ...
答案 0 :(得分:1)
SELECT * FROM TABLE o
WHERE o.readingDate = (
SELECT MAX(e.readingDate) FROM TABLE e
WHERE e.tdName = o.tdName
);
答案 1 :(得分:0)
实际上我发现我的答案与其他答案非常接近。返回所有字段的完整选择查询如下:
select
t1.name,
t1.max,
t2.due_date,
t2.fixed_rate,
t2.unit_price,
t2.reading_time
from (select
t2.name,
max(t2.reading_date)
from td t2
where
t2.due_date > now()
group by t2.name) t1,
td t2
where
t1.name = t2.name
and t1.max = t2.reading_date;