2012-03-19 9 views
5

estoy tratando de hacer el equivalente de este código SQL¿Cómo hacer una suma condicional con 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 

Con Nhibernate.

Hasta ahora he intentado

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) 
) 

Pero esto me da el siguiente error:

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

¿Tiene usted alguna idea?

EDIT 1: Puedo obtener el resultado con 2 consultas, pero quiero hacerlo en solo 1 consulta.

EDIT 2: Estoy usando QueryOver aquí.

+0

Parece que es mejor usar 'COUNT' en lugar de' SUM' . – yoozer8

+0

Count no acepta condiciones, ¿cómo podría usarlo aquí? Dos consultas? –

+0

Si no acepta consultas, puede usar 'WHERE' para seleccionar solo las que desea contar y luego use' COUNT'. – yoozer8

Respuesta

14

creo que esto debería funcionar (sintaxis 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)))); 

que debe dar el siguiente 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

¿Sabes cómo se verá si utilizo QueryOver en su lugar? –

+0

@AlexeyZimarev: El código de arriba * es * QueryOver ... –

+0

Me refiero a usar SelectGroup en lugar de Projections.Group, SelectSum en lugar de Projections.Sum y así sucesivamente, así QueryOver con sintaxis en línea para ser precisos con los términos –

Cuestiones relacionadas