2

此 sql 查询的 linq 查询是什么

SELECT 
      sum(IIF(jenis = 'primer',1,0)) as sum_primer, 
      sum(IIF(jenis = 'sekunder',1,0)) as sum_sekunder
FROM cooperations

尝试从 101 个 Linq 样本中搜索相同的示例,但没有任何线索

更新 所以,我在我的 C# 中使用这个查询

var query = (from c in db_cooperations.cooperations
              group c by c.jenis into g
              select
              (new
              {
                sum_primer = g.Count(c => c.jenis == "primer"),
                sum_sekunder = g.Count(c => c.jenis == "sekunder")
              })).ToArray();

输出是

 sum_primer   sum_sekunder
    0             0 
    0             52
   250            0
    0             0
    0             0

那么,我怎样才能删除零值,只返回一行

4

2 回答 2

5
var sum_primer = cooperations.Count(c => c.jenis == "primer");
var sum_secunder = cooperations.Count(c => c.jenis == "sekunder");

或在对数据库的单个查询中

var query = (from c in cooperations
             where c.jenis == "primer" || c.jenis == "sekunder"
             group c by c.jenis
             select new { Jenis = g.Key, Count = g.Count() }
            ).ToDictionary(x => x.Jenis, x => x.Count);

var result = new {
   sum_primer = query.ContainsKey("primer") ? query["primer"] : 0,
   sum_sekunder = query.ContainsKey("sekunder") ? query["sekunder"] : 0
};

将生成此 SQL(并且只返回两行):

SELECT COUNT(*) AS [Count], [t0].[jenis] AS [Jenis]
FROM [cooperations] AS [t0]
WHERE ([t0].[jenis] = 'sekunder') OR ([t0].[jenis] = 'primer')
GROUP BY [t0].[jenis]
于 2013-01-29T07:10:12.260 回答
5

您可以像这样实现它,以下是根据条件为您提供项目的计数

var data = db.CoOperations.
           GroupBy(x=>x.jenis )
           .select (new {
                sum_primer = g.Count(c => c.jenis == "primer"),
                sum_sekunder = g.Count(c => c.jenis == "sekunder"),
            });
于 2013-01-29T07:11:12.670 回答