-1

I have this SQL Server query and want to convert this to 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]

The result of this above query is in pic perfect but I need a total of all row in Total column:

OutPut

Data is stored like:

CompanyName | Month | Sale
H&S         |  Jan  | 1200
H&S         |  Feb  | 5000 
H&S1        |  March| 8000 

But I want to display like:

CompanyName| Jan |  Feb | March | Total
H&S        |1200 | 5000  | 7000 | 13200
H&S1       |2200 | 6000  | 8000 | 16200

and show same data on View

NetMage
  • 24,279
  • 3
  • 31
  • 50

1 Answers1

0

As you haven't provided any dbcontext or entity structure, the linq query will look like below for Jan-June sales and total. You need to group the rows by companyname (Location) and then use conditional values in aggregate function 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)
            });
Vinit
  • 2,464
  • 1
  • 12
  • 21