0

我有一个像下面这样的 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 编写合并,以及行的顺序是否正确。有什么线索吗?

4

1 回答 1

1

使用Projections.sqlGroupProjection(...)与标准如下

    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;

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

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

看看这是否有帮助,您可能想根据您的数据对其进行测试。

于 2016-01-21T12:15:34.393 回答