[英]SQL command to LINQ (pivoting)
I'm moving DB from MySQL (used ODBC) to MS SQL and I want to "translate" SQL queries to LINQ. 我正在将数据库从MySQL(使用ODBC)转移到MS SQL,我想将SQL查询“转换”为LINQ。 Can someone help me with this (it should SUM Charge column for every location and group result by months): 有人可以帮我这个(它应该为每个位置的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
? ?
Output should look like this: 输出应如下所示:
Location1 | Location2 | Location3 | date
EDIT: 编辑:
I tryed to use LINQ sample from here: 我试着从这里使用LINQ示例:
Is it possible to Pivot data using 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();
and it is almost what I need. 这几乎是我的需要。 There should be grouping by year too and I don't know how to do this. 应该按年分组,我不知道该怎么做。
This might help. 这可能有所帮助。
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);
.. do You know maybe how to make adding Locations to Select dynamically? ..你知道如何动态添加Locations to Select吗? For example from List/Array. 例如,从List / Array。
EDIT: .. or maybe making Locations to load dynamically and setting which Locations should be loaded in Where statement before Select. 编辑:..或者可能使位置动态加载并设置应在Select之前的Where语句中加载哪些位置。 Is this possible? 这可能吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.