有没有办法在 HQL 中执行以下操作:

SELECT 
    case when flag = true then SUM(col1) else SUM(col2)
FROM 
    myTable
有帮助吗?

解决方案

我想你可以(3.6, 4.3) [内联编辑] ...对于 where 子句:

“简单”的情况, case ... when ... then ... else ... end, ,以及“搜索”案例, case when ... then ... else ... end

其他提示

显然要做到这一点是在3.0.4 添加的能力与你不能在else子句中使用子选择的限制。

请参阅休眠-论坛: https://forum.hibernate.org/viewtopic.php ΔT= 942197个

从小组(加文)答: 情况下被支撑在where子句中,但不是在HB3选择子句英寸

和在JIRA与国家看到 “未解决”。

下面你可以找到一个工作查询(休眠上的PostgreSQL),其使用2个case语句来替换相应的文本表示一个布尔值。

  

当真实THEN SELECT CASE ps.open   'OPEN' 其他 '封闭' END,CASE   ps.full WHEN真,那么“FULL”其他   'FREE' END,ps.availableCapacity   FROM ParkingState作为PS

我们使用广泛休眠HQL查询,我觉得终于有做这样的事的hackish的方式:

假设我们原本的查询

i2.element.id = :someId

然后决定扩大这是这样的:

((i.element.id = :someId and i2.element.id=:someId) or (i2.element.id = :someId))

但是有,我们希望它不仅查找此基础上classType所的问题,所以一个case语句:

(case when type(i)=Item then 
((i.element.id = :someId and i2.element.id=:someId) or (i2.element.id = :someId))
else
i.element.id = :someId
end)

以上都不行,你可以这样做使一个简单的版本的上述工作:

(case when type(i)=Item then 
i2.element.id
else
i.element.id
end)=:elementId

但是,这实际上并没有做什么,我们需要做的,我们希望它做的确切上面的查询,所以知道你可以在一个case语句在那里结束指定一个变量,其中HQL位:

(
                            (
                                (case when 
                                    type(r)=Item then 
                                        i.element.id 
                                    else 
                                        i.element.id end) = :elementId 
                                and 
                                (case when 
                                    type(r)=Item then 
                                        i2.element.id 
                                    else 
                                        i.element.id end) = :elementId
                            )
                            or 
                            (case when 
                                    type(r)=Item then 
                                        i2.element.id 
                                    else 
                                        i.element.id end) = :elementId 
                            )

我已成功地使查询工作现在基于case语句,确保它是一个很大的长篇大论,但实际上做一样的一审

我面临HQL同样的问题然后我解决以下查询是

select CONCAT(event.address1,', ', CASE WHEN event.address2 IS NULL THEN '' ELSE concat(event.address2,', ') END, event.city from EventDetail event where event.startDate>=:startDate and event.endDate<=:endDate;

这是一个使用在条件字符串比较的示例:

SELECT CASE f.type WHEN 'REMOVE'
                   THEN f.previousLocation 
                   ELSE f.currentLocation 
       END 
FROM FileOperation f
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top