SQL command for LINQ (rotation)

I am moving DB from MySQL (using ODBC) to MS SQL, and I want to "translate" SQL queries into LINQ. Can anyone help me with this (it should column SUM Charge for each location and group result by month):

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 

?

The result should look like this:

Location1 | Location2 | Location3 | date

EDIT:

I tried using the LINQ sample from here:

Is it possible to collapse data using 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 that’s almost what I need. There, too, you need to group, and I do not know how to do it.

+3
source share
2 answers

This can 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);
+6
source

.. know maybe how to add locations to select dynamically? For example, from a list / array.

:.. , , , Where Select. ?

0

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


All Articles