SQL命令到LINQ(数据透视)



我正在将数据库从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样本:

是否可以使用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();

这几乎是我所需要的。也应该按年份分组,我不知道该怎么做。

这可能会有所帮助。

context.log_sales
.GroupBy(s => new {Year = OrderTime.Year, Month = OrderTime.Month})
.Select
( g => new {
  Date = new DateTime(g.Key.Year, g.Key.Month, 1),
  Location1 = g.Where(s => s.Location == "Location1").Sum(s => s.Charge),
  Location2 = g.Where(s => s.Location == "Location2").Sum(s => s.Charge),
  Location3 = g.Where(s => s.Location == "Location3").Sum(s => s.Charge),
  }
)
.OrderBy(x => x.Date);

。。你知道如何动态添加要选择的位置吗?例如,来自List/Array。

编辑:。。或者可以使位置动态加载,并在选择之前在Where语句中设置应加载的位置。这可能吗?

相关内容

  • 没有找到相关文章

最新更新