在JPA中按“CASE列”排序

时间:2011-10-31 19:09:11

标签: jpa jpql

我想通过案例陈述订购,是否可能?我该怎么办?

SELECT new com.systemname.to.UserDataHolder(u.userId, 
CASE  WHEN (u.place.cityId = :cityId) THEN 1  WHEN (u.place.stateId = :stateId) THEN 2  ELSE 3 END)  
FROM User u 
ORDER BY u.userId DESC 

2 个答案:

答案 0 :(得分:7)

您使用的是哪个JPA提供商?

尝试,

SELECT u.userId, 
(CASE  
    WHEN (u.place.cityId = :cityId) THEN 1
    WHEN (u.place.stateId = :stateId) THEN 2
    ELSE 3 END) as myNum
FROM User u 
ORDER BY u.userId, myNum DESC

,或者

SELECT new com.systemname.to.UserDataHolder(u.userId, 
CASE  
    WHEN (u.place.cityId = :cityId) THEN 1
    WHEN (u.place.stateId = :stateId) THEN 2
    ELSE 3 END)
FROM User u 
ORDER BY u.userId, CASE  
    WHEN (u.place.cityId = :cityId) THEN 1
    WHEN (u.place.stateId = :stateId) THEN 2
    ELSE 3 END DESC

答案 1 :(得分:0)

目前无法测试,所以我不确定这是否是有效的语法,但是你可以添加一个“AS”吗?

SELECT new com.systemname.to.UserDataHolder(u.userId, 
CASE  
    WHEN (u.place.cityId = :cityId) THEN 1
    WHEN (u.place.stateId = :stateId) THEN 2
    ELSE 3 END as myNum)
FROM User u 
ORDER BY u.userId, myNum DESC