将SQL CASE WHEN语句和组语句转换为LINQ

时间:2012-01-03 11:13:33

标签: sql-server linq-to-sql group-by case-when

如何用流畅的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可能吗?

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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();

答案 2 :(得分: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在尝试让它发挥作用方面非常有用。