【问题标题】:How to use case and order by in Nhibernate?如何在 Nhibernate 中使用 case 和 order by?
【发布时间】:2012-01-22 13:14:44
【问题描述】:

我需要通过typeId我自己的方向 在 DB 表 ChargeOperations 中订购结果。 SQL请求是这样的:

SELECT * FROM ChargeOperations co
LEFT JOIN ShadowChargeOperations sco ON sco.ChargeOperationId=co.Id
-- just exclude some extra data.
WHERE sco.Id IS NULL
ORDER BY
 CASE co.TypeId
  WHEN 1 THEN 3   -- this is my order, which is different from id of type and can change
  WHEN 2 THEN 1
  WHEN 3 THEN 2
  ELSE 4
 END,
 co.TypeId,
 co.CalculationAmount

那么,请你给我一个如何创建这个结构的例子。

CASE co.TypeId 
  WHEN 1 THEN 3   -- this is my order, which is different from id of type and can change
  WHEN 2 THEN 1
  WHEN 3 THEN 2
  ELSE 4

使用 QueryOver。

【问题讨论】:

  • TypeId 鉴别器值吗?你需要分页吗?
  • 我不知道你的意思是鉴别器值。 TypeId 是用于排序的字段。我不需要分页或其他东西。我知道如何使用 HQL 创建它,但我们使用 queryOver...

标签: hibernate nhibernate sql-order-by case queryover


【解决方案1】:

您可以使用Projections.Conditional 进行操作,例如:

ChargeOperation itemAlias = null;

var result = 
    session.QueryOver<ChargeOperation>(() => itemAlias)
            .Where ( /*your conditions*/)
            .OrderBy(Projections.Conditional(
                        Restrictions.Where(() => itemAlias.TypeId == 1),
                        Projections.Constant(3),                                
                    Projections.Conditional(
                        Restrictions.Where(() => itemAlias.TypeId == 2),
                        Projections.Constant(1),
                    Projections.Conditional(
                        Restrictions.Where(() => itemAlias.TypeId == 3),
                        Projections.Constant(2),
                        )
                    )           
                )                           
            ).Asc
            .ThenBy(x => x.TypeId)
            .ThenBy(x => x.CalculationAmount)
        .List();

【讨论】:

  • 即使是很老的问题,也让它成为答案吧 :) 我就是查不出来。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-17
  • 1970-01-01
相关资源
最近更新 更多