Sales are grouped by month, then by product

I want to get a sales list for each month ordered by the product.

I currently have the following linq request:

        var query = storeDB.OrderDetails
            .Select(od => od)
            .GroupBy(r => r.Product)
            .Select(group => new ProductSalesModel {
                Product = group.Key,
                Sales = group.Sum(s => s.Quantity),
                Amount = group.Sum(s => s.Quantity * s.UnitPrice)
            })
            .OrderByDescending(x => x.Amount);

How can I do to also group the list by month, getting the sale date from my order table? Order.CreationDate?

+3
source share
2 answers

I don’t know which Linq provider you are trying to use, but in regular Linq this should work:

 .GroupBy(r => new {r.Product, r.CreationDate})

and then when you select:

.Select(group => new ProductSalesModel {
                Product = group.Key.Product,
                CreationDate = group.Key.CreationDate,
                Sales = group.Sum(s => s.Quantity),
                Amount = group.Sum(s => s.Quantity * s.UnitPrice)
            })
+2
source

If you want to order something, it must be in a grouping. Then you can useOrderByDescending(t=> t.amount).ThenBy(y => y.OrderDate)

0
source

Source: https://habr.com/ru/post/1783000/


All Articles