2012-03-19 61 views
5

我试图做到这一点SQL代码如何与Nhibernate做一个条件和?

SELECT 
ID 
SUM(CASE WHEN myProperty = 2 THEN 1 ELSE 0 END) as nbRowWithValueOf2, 
SUM(CASE WHEN myProperty = 3 THEN 1 ELSE 0 END) as nbRowWithValueOf3 
FROM Foo 
GROUP BY ID 

与NHibernate的等价物。

到目前为止,我试过

queryable = queryable 
    .Select(
     Projections.Group<Foo>(c => c.ID), 
     Projections.Sum<Foo>(c => c.myProperty == MyEnum.Two ? 1 : 0) 
     Projections.Sum<Foo>(c => c.myProperty == MyEnum.Three ? 1 : 0) 
) 

但是这给了我以下错误:

Could not determine member from IIF((Convert(c.myProperty) = 2), 1, 0)

你有什么想法?

编辑1:我可以得到2查询的结果,但我只想在1查询中做到这一点。

编辑2:我在这里使用QueryOver。

+0

看起来你应该使用'COUNT'代替SUM'的' 。 – yoozer8 2012-03-19 16:55:21

+0

伯爵不接受条件,我怎么能在这里使用它?两个查询? – 2012-03-19 16:57:19

+0

如果它不接受查询,你可以使用'WHERE'来选择你想要计数的数字,然后使用'COUNT'。 – yoozer8 2012-03-19 17:00:22

回答

14

我认为这应该工作(QueryOver语法):

queryover = queryover 
    .Select(
     Projections.Group<Foo>(c => c.ID), 
     Projections.Sum(
      Projections.Conditional(
       Restrictions.Where<Foo>(f => f.myProperty == MyEnum.Two), 
       Projections.Constant(1), 
       Projections.Constant(0))), 
     Projections.Sum(
      Projections.Conditional(
       Restrictions.Where<Foo>(f => f.myProperty == MyEnum.Three), 
       Projections.Constant(1), 
       Projections.Constant(0)))); 

这应该给你的SQL语句:

SELECT this_.ID as y0_, 
     sum((case 
       when this_.myProperty = 2 /* @p0 */ then 1 /* @p1 */ 
       else 0 /* @p2 */ 
      end))    as y1_, 
     sum((case 
       when this_.myProperty = 3 /* @p3 */ then 1 /* @p4 */ 
       else 0 /* @p5 */ 
      end))    as y2_ 
FROM [Foo] this_ 
GROUP BY this_.ID 
+0

你知道如果我使用QueryOver而不是这样吗? – 2012-06-26 14:45:43

+0

@AlexeyZimarev:*上面的代码是* QueryOver ... – 2012-06-26 14:46:16

+0

我的意思是使用SelectGroup而不是Projections.Group,SelectSum而不是Projections.Sum等等,所以QueryOver与内联语法是精确的术语 – 2012-06-27 08:15:38