我有此SQL Server查询,并想将其转换为Linq:
SELECT
[FMonth],
[Locationn],
(SELECT SUM(Sale) FROM [Fuels] WHERE FMonth = 1) AS Jan,
(SELECT SUM(Sale) FROM [Fuels] WHERE FMonth = 2) AS Feb,
(SELECT SUM(Sale) FROM[Fuels] WHERE FMonth = 3) AS March,
(SELECT SUM(Sale) FROM [Fuels] WHERE FMonth = 4) AS April,
(SELECT SUM(Sale) FROM [Fuels] WHERE FMonth = 5) AS May,
(SELECT SUM(Sale) FROM [Fuels] WHERE FMonth = 6) AS Jun,
(SELECT SUM(Sale) FROM [Fuels] WHERE FMonth = 7) AS Jul,
(SELECT SUM(Sale) FROM [Fuels] WHERE FMonth = 8) AS Aug
FROM
[COSAuthNew].[dbo].[Fuels]
以上查询的结果是完美的图片,但我需要Total
列中的所有行的总和:
数据存储方式如下:
CompanyName | Month | Sale
H&S | Jan | 1200
H&S | Feb | 5000
H&S1 | March| 8000
但我想显示为:
CompanyName| Jan | Feb | March | Total
H&S |1200 | 5000 | 7000 | 13200
H&S1 |2200 | 6000 | 8000 | 16200
并在视图上显示相同的数据
答案 0 :(得分:0)
由于您没有提供任何dbcontext或实体结构,因此linq查询如下所示,显示了1月至6月的销售额和总计。您需要按公司名称(位置)对行进行分组,然后在聚合函数SUM中使用条件值。
var result = fules.GroupBy(g => g.CompanyName)
.Select(s=> new {
CompanyName = s.Key,
Jan = s.Sum(x=> x.Month == 1? x.Sale : 0),
Feb = s.Sum(x => x.Month == 2 ? x.Sale : 0),
Mar = s.Sum(x => x.Month == 3 ? x.Sale : 0),
Apr = s.Sum(x => x.Month == 4 ? x.Sale : 0),
May = s.Sum(x => x.Month == 5 ? x.Sale : 0),
June = s.Sum(x => x.Month == 6 ? x.Sale : 0),
Total = s.Sum(x=> x.Sale)
});