3

我想为查询编写分离标准。

SELECT Id, sum(1) as total 
    ,sum(CASE WHEN e.salary > 2000 THEN e.salary
         ELSE 2000 END) "total Salary" 
FROM employees e;

有人可以帮忙吗?

4

1 回答 1

1

我们可以这样做:

首先让我们创建条件,稍后计算:

var computed = Projections.Conditional(
    Restrictions.Gt("Salary", 2000)
    , Projections.Property("Salary")
    , Projections.Constant(2000));

此时,我们将 CASE 语句包裹在computed投影中。所以让我们使用它:

var session = ... // get the ISession 

// criteria querying the Employee
var criteria = session.CreateCriteria<Employee>();

// the projections we need
criteria.SetProjection(
    Projections.ProjectionList()
        .Add(Projections.GroupProperty("Id"), "Id")
        .Add(Projections.Sum(Projections.Constant(1)), "Total")
        .Add(Projections.Sum(computed), "Salary")
    );

// result transformer, converting the projections into EmployeeDTO
var list = criteria
    .SetResultTransformer(Transformers.AliasToBean<EmployeeDTO>())
    .List<EmployeeDTO>();

And this could be our EmployeeDTO, if Salary is int:

public class EmployeeDTO
{
    public virtual int ID { get; set; }
    public virtual int Total { get; set; }
    public virtual int Salary { get; set; }
}
于 2013-10-15T04:18:25.663 回答