在加入过程中,我得到下表(示例):

+----------+----------+
| Hostname | Severity |
+----------+----------+
| host1    |   high   |
| host2    |  medium  |
| host1    |   high   |
| host2    |   low    |
| host1    |   low    |
| host2    |   low    |
| host1    |   low    |
| host2    |   high   |
| host1    |   high   |
| host2    |   high   |
+----------+----------+


是否可以创建I JPQL查询,并得到以下结果:

+----------+------+--------+-----+
| Hostname | high | medium | low |
+----------+------+--------+-----+
| host1    |  3   |   0    |  2  |
| host2    |  2   |   1    |  2  |
+----------+------+--------+-----+


我尝试使用COUNTGROUP BY,但是得到了类似的内容:

host1,high,3
host1,medium,0
host1,low,2


等等...

BR,Rene

最佳答案

一个标准的sql查询看起来像这样-我不确定所使用的API需要付出什么努力,但是它通过大小写逻辑非常简单地组合在一起。

select hostname,
  sum(case when severity = 'high' then 1 else 0 end) as high,
  sum(case when severity = 'medium' then 1 else 0 end) as medium,
  sum(case when severity = 'low' then 1 else 0 end) as low
from
  Table
group by
  hostname
order by
  hostname

关于java - Java Hibernate JPQL查询(汇总功能:计数),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7064618/

10-10 09:05