我有一个实体类
public class TeklaEventE {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private Integer projectId;
private Integer drawingId;
private Integer userId;
private String eventType;
private LocalDateTime eventDate;
private LocalDateTime modifiedDate;
private String projectName;
private String userName;
private transient int noOfUser;
// getter setter
}
我想通过对* , COUNT(DISTINCT userId)
进行排序来对projectId
进行分组来获得eventDate
我尝试了以下查询
SELECT *,COUNT(DISTINCT userId) as noOfUser FROM teklaevent group by projectId order by eventDate desc;
它给出正确的计数,但是它首先运行group by
,然后运行order by
,但是我需要具有不同的projectId
的最新行。然后我尝试按照建议的第二个查询
select * FROM TeklaEvent where id in (select max(id) FROM TeklaEvent group by projectId) order by eventDate desc;
可以完美地显示我需要的行,因为eventDate
始终是当前日期。但是,当我尝试从下面的查询中获取COUNT(DISTINCT userId)
时。
select *,COUNT(DISTINCT userId) as noOfUser FROM TeklaEvent where id in (select max(id) FROM TeklaEvent group by projectId) order by eventDate desc;
无法给我正确的结果。
如何在单个查询中执行此操作?
答案 0 :(得分:1)
您可以在子选择上使用联接作为计数
Products
答案 1 :(得分:0)
这对我有用:
select a.*, t.noOfUser
from teklaevent a
inner join (
select max(id) maxid, count(distinct userId) noOfUser
from teklaevent
group by projectId
) t on a.id = t.maxid;