【问题标题】:Criteria to apply Restrictions and Projection then count distinct results应用限制和投影的标准然后计算不同的结果
【发布时间】:2013-11-05 12:23:04
【问题描述】:

我正在尝试使用 Criteria 执行以下功能,但它给了我一个运行时错误,指示 SQL 中的错误。

 var query = session.CreateCriteria<TableName>()
                       .Add(Restrictions.Disjunction()
                            .Add(Restrictions.InsensitiveLike("Property1", keyword, MatchMode.Anywhere))
                            .Add(Restrictions.InsensitiveLike("Property2", keyword, MatchMode.Anywhere)));

query.SetProjection(Projections.Count(Projections.Distinct(
                                    Projections.ProjectionList()
                                    .Add(Projections.Property("Property1"))
                                    .Add(Projections.Property("Property3"))
                                    )));

表映射如下所示:

public class TableName
{
     public int Property1 {get;set;}
     public int Property2 {get;set;}
     public int Property3 {get;set;}
     public int Property4 {get;set;}
}

我需要根据我的预测计算不同的结果,我不想将结果计算为一整行!

谁能帮我解决这个问题?

----------更新---------

这就是我想要完成的:

select Count(*)

from 
(
    select distinct Property1 , Property2 
    from tableName
    where Property1 like '%t%' or Property3 like '%t%'
) As x

【问题讨论】:

    标签: linq asp.net-mvc-4 nhibernate count distinct


    【解决方案1】:

    您的条件(如果可以翻译的话)会产生如下 SQL:

    SELECT count(DISTINCT Property1, Property3) 
    FROM TableName 
    WHERE Property1 LIKE '%keyword%' OR Property2 LIKE '%keyword%'
    

    这是行不通的。使用

    Projections.RowCount()  or  Projections.RowCountInt64()
    

    对于 COUNT(*) 等效项。 可能,一个 GROUP BY 子句是有意义的(而不是 DISTINCT)。 (我希望您在使用 LIKE '%keyword%' 进行搜索时不需要 Int64 结果计数!;-)

    【讨论】:

    • 我已经尝试过 RowCount,但它并不能消除仅在两列上进行投影时产生的重复行!这就是我需要的!
    • 请检查上面的问题更新
    • 我想我现在无能为力,必须自己找出答案。我的想法是 count(...) with group by,但它只会计算分组到一行中的重复项的数量,而不是所有结果行。
    猜你喜欢
    • 2015-05-03
    • 1970-01-01
    • 2012-09-06
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 2015-07-17
    • 1970-01-01
    相关资源
    最近更新 更多