NVL2等同于标准

时间:2016-01-21 10:32:48

标签: sql hibernate nvl

我有一个类似下面的SQL查询

select name, loc, status, proj, nbr, sum(sub) as sub, nvl2(val, ''Y'', ''N'') where name = "value" group by name, loc, status, proj, nbr, nvl2(val, ''Y'', ''N'')

我尝试使用标准

编写相同的内容
ProjectionList proList = Projections.projectionList();
proList.add(Projections.sum("sub"));
criteria.add(Restrictions.like("name", StringUtils.appendWildCard("value")).ignoreCase());              
criteria.addOrder(Order.asc("value"));      

我想知道如何为nvl编写coalesce,以及如果行的顺序是正确的。 任何线索?

1 个答案:

答案 0 :(得分:1)

使用Projections.sqlGroupProjection(...)和Criteria,如下所示

    List<CoalesceDemo> list = session.createCriteria(CoalesceDemo.class).
        setProjection(Projections.projectionList()
                .add(Projections.sum("sub"))
                .add(Projections.sqlGroupProjection("nvl2(val, 'Y', 'N') as decodedVal", "nvl2(val, 'Y', 'N')", 
new String [] {"decodedVal"}, new Type[]{BooleanType.INSTANCE}))
                .add(Projections.groupProperty("name"))
                .add(Projections.groupProperty("val"))
                .add(Projections.groupProperty("nbr"))
                .add(Projections.groupProperty("proj"))
                .add(Projections.groupProperty("loc")))
        .add(Restrictions.eq("name", "value")).list();

导致您正在寻找以下查询:

select this_.name as y0_, this_.loc as y1_, this_.nbr as y2_, this_.proj as y3_, sum(this_.sub) as y4_, 
nvl2(val, 'Y', 'N') as decodedVal, this_.name as y6_, this_.val as y7_, this_.nbr as y8_, 
this_.proj as y9_, this_.loc as y10_ from CoalesceTable this_ where this_.name=? 
group by nvl2(val, 'Y', 'N'), this_.name, this_.val, this_.nbr, this_.proj, this_.loc

另一种方法是在实体的新字段上使用@Formula注释。

就我而言,我已在CoalesceDemo

中添加了此字段
@Formula("nvl2(val, 'Y', 'N')")
public String decodedVal;

并在Criteria查询中使用它,如下所示:

List<CoalesceDemo> list = session.createCriteria(CoalesceDemo.class).
    setProjection(Projections.projectionList()
            .add(Projections.sum("sub"))
            .add(Projections.groupProperty("name"))
            .add(Projections.groupProperty("val"))
            .add(Projections.groupProperty("nbr"))
            .add(Projections.groupProperty("proj"))
            .add(Projections.groupProperty("decodedVal"))
            .add(Projections.groupProperty("loc")))
    .add(Restrictions.eq("name", "value")).list();

这导致查询如下:

select this_.name as y0_, this_.loc as y1_, this_.nbr as y2_, this_.proj as y3_, sum(this_.sub) as y4_, 
this_.name as y5_, this_.val as y6_, this_.nbr as y7_, this_.proj as y8_, 
nvl2(this_.val, 'Y', 'N') as y9_, this_.loc as y10_ from CoalesceTable this_ where this_.name=? 
group by this_.name, this_.val, this_.nbr, this_.proj, nvl2(this_.val, 'Y', 'N'), this_.loc

看看这是否有帮助,您可能希望针对您的数据进行测试。