我想编写独立的查询条件。
SELECT Id, sum(1) as total
,sum(CASE WHEN e.salary > 2000 THEN e.salary
ELSE 2000 END) "total Salary"
FROM employees e;
有人可以帮忙吗?
最佳答案
我们可以这样:
首先让我们创建条件,稍后再计算:
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,这可能是我们的EmployeeDTO:
public class EmployeeDTO
{
public virtual int ID { get; set; }
public virtual int Total { get; set; }
public virtual int Salary { get; set; }
}