3

如何以流利的 linq 语法编写“case when”sql 语句?

select QueueItem, COUNT(*) as [Count],
SUM(CASE WHEN Queued = 0 THEN 1 ELSE 0 END) AS [Sent],
SUM(CASE WHEN Queued = 1 THEN 1 ELSE 0 END) AS Queued,
SUM(CASE WHEN Success = 1 THEN 1 ELSE 0 END) AS Exported,
SUM(CASE WHEN Success = 0 THEN 1 ELSE 0 END) AS Failed
from ExportQueue x
group by QueueItem

有没有可以将 SQL 转换为 LINQ 的程序?LinqPad 也许?

4

3 回答 3

4

好的,像这样。我需要一些信息来确定

是不是有点排队?这在 linq 中有所不同,而在 SQL 中则没有。我也不知道你的上下文名称,但你应该明白。

var query = Context.ExportQueues.Select(x => new { 
  QueueItem = x.QueueItem, 
  Sent = !x.Queued ? 1 : 0,
  Queued = x.Queued ? 1 : 0,
  Exported = x.Success ? 1 : 0,
  Failed = !x.Success ? 1 : 0 })
.GroupBy(x => x.QueueItem)
.Select(g => new { 
  QueueItem = g.Key,
  Sent = g.Sum(x => x.Sent),
  Queued = g.Sum(x => x.Queued),
  Exported = g.Sum(x => x.Exported),
  Failed = g.Sum(x => x.Failed)
}).ToList();

编辑您还可以通过在查询中即时执行案例来组合这些。当我完成它时,我总是倾向于先把它写出来,尽管如果出现错误,更复杂的聚合可能有点难以调试:

var query = Context.ExportQueues
.GroupBy(x => x.QueueItem)
.Select(g => new { 
  QueueItem = g.Key,
  Sent = g.Sum(x => !x.Queued ? 1 : 0),
  Queued = g.Sum(x => x.Queued ? 1 : 0),
  Exported = g.Sum(x => x.Success ? 1 : 0),
  Failed = g.Sum(x => !x.Success ? 1 : 0 )
}).ToList();
于 2012-01-03T11:27:22.480 回答
2

作为 Gatts 解决方案的替代方案,您可以执行以下操作

var query = Context.ExportQueues.
.GroupBy(x => x.QueueItem)
.Select(g => new { 
  QueueItem = g.Key,
  Sent = g.Count(x=>!x.Queued),
  Queued = g.Count(x => x.Queued),
  Exported = g.Count(x => x.Success),
  Failed = g.Count(x => !x.Failed)
}).ToList();
于 2012-01-03T11:40:03.750 回答
0

使用 LINQ 编写这实际上是相当冗长的。您需要做的是先分组,然后使用 lambda 表达式来处理聚合。所以像:

from eq in ExportQueue
group eq by new {
    eq.QueueItem
} into temp
select new {
    temp.Key.QueueItem,
    Agg1 = temp.Sum(n => n.Queued == 0 ? 1 : 0),
    Agg2 = temp.Sum(n => n.Queued == 1 ? 1 : 0)
}

依此类推,LinqPad 在尝试使其正常工作时将非常有用。

于 2012-01-03T11:34:33.277 回答