我正在将数据库从 MySQL(使用 ODBC)移动到 MS SQL,并且我想将 SQL 查询“翻译”到 LINQ。有人可以帮我解决这个问题(它应该为每个位置和按月分组结果的 SUM Charge 列):
SELECT
sum(case when Location="Location1" then Charge else 0 end) as Location1,
sum(case when Location="Location2" then Charge else 0 end) as Location2,
sum(case when Location="Location3" then Charge else 0 end) as Location3,
MAKEDATE(YEAR(OrderTime),DAYOFYEAR(OrderTime)) AS date FROM Sales
GROUP BY YEAR(OrderTime),MONTH(OrderTime)
ORDER BY OrderTime DESC
?
输出应如下所示:
Location1 | Location2 | Location3 | date
编辑:
我尝试从这里使用 LINQ 示例:
var query = context.log_sales
.GroupBy(c => c.OrderTime)
.Select(g => new
{
Date = g.Key,
Location1 = g.Where(c => c.Location == "Location1").Sum(c => c.Charge) ?? 0,
Location2 = g.Where(c => c.Location == "Location2").Sum(c => c.Charge) ?? 0
}).ToList();
这几乎是我所需要的。也应该按年份分组,我不知道该怎么做。