'How to get Percentage of Sales for the Past 5 Years

In my ASP.NET Core-5 Entity Framework I have this model:

public class Sales
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Amount { get; set; }
    public DateTime? SalesDate { get; set; }
}

DTO:

public class YearlyPercentDto
{
    public decimal SalesTotal { get; set; }
    public int SalesPercent { get; set; }
    public string Year { get; set; }
}

public List<YearlyPercentDto> GetYearlySalesSummary()
{
    var salesDetail = _context.sales               
        .GroupBy(o => new
        {
            Year = o.CreatedDate.Value.Year
        })
        .Select(u => new YearlyPercentDto
        {
            SalesPercent = u.Sum(x => x.Amount),
            Year = u.Key.Year.ToString()
        }).ToList();
    return salesDetail;
}

I want to get the total_sales, percentage_sales for each year in the past 5 years as shown below:

Year (Past 5 Years)    SalesTotal     SalesPercent

2021                     200000       18
2020                     4300000
2019                     1290000
2018                     5400000 
2017                     3322220

How do I achieve this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source