我想为查询编写分离标准。
SELECT Id, sum(1) as total
,sum(CASE WHEN e.salary > 2000 THEN e.salary
ELSE 2000 END) "total Salary"
FROM employees e;
有人可以帮忙吗?
答案 0 :(得分: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>();
如果Salary是int:
,这可能是我们的EmployeeDTOpublic class EmployeeDTO
{
public virtual int ID { get; set; }
public virtual int Total { get; set; }
public virtual int Salary { get; set; }
}