Domanda

Sto spostando i DB da MySQL (usato ODBC) a MS SQL e desidero " tradurre " Query SQL su LINQ. Qualcuno può aiutarmi in questo (dovrebbe essere la colonna SUM Charge per ogni posizione e risultato del gruppo per mesi):

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 

L'output dovrebbe essere simile al seguente:

Location1 | Location2 | Location3 | date

EDIT:

Ho provato a utilizzare l'esempio LINQ da qui:

È possibile eseguire il pivot dei dati utilizzando 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();

ed è quasi ciò di cui ho bisogno. Dovrebbe esserci anche un raggruppamento per anno e non so come farlo.

È stato utile?

Soluzione

Questo potrebbe aiutare.

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);

Altri suggerimenti

.. sai forse come aggiungere dinamicamente posizioni a Select? Ad esempio da Elenco / Matrice.

MODIFICA: .. o forse facendo caricare le posizioni in modo dinamico e impostando quali posizioni dovrebbero essere caricate nell'istruzione Where prima di Seleziona. È possibile?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top