Pivot contro una stored procedure SQL (o LINQ)
Domanda
Sto cercando di creare una stored procedure (o espressione di query), che fa perno su un ID di raggruppamento. Dopo aver esaminato gli esempi qui e altrove ho fallito di ottenere le mie dichiarazioni perno di lavorare in una stored procedure, e sto cercando il mio aiuto.
Inoltre, se questo potrebbe essere fatto con LINQ in un elenco che sarebbe una soluzione per me anche.
theID theGroup theValue
1 2 Red
2 2 Blue
3 2 Green
1 3 10
2 3 24
3 3 30
1 4 1
2 4 2
3 4 3
Il Gruppo # 2 significa una scelta, il gruppo # 3 mezzi contano, il Gruppo # 4 significa ORDINA quindi voglio nominare quelle colonne (mi rendo conto che questo è un difetto della PIVOT ma va bene).
ID CHOICE COUNT SORT
1 Red 10 1
2 Blue 24 2
3 Green 30 3
Soluzione
Questo ha funzionato per me e dovrebbe funzionare in un SP:
SELECT theID AS ID
,[2] AS CHOICE
,[3] AS COUNT
,[4] AS SORT
FROM so_666934 PIVOT ( MAX(theValue) FOR theGroup IN ([2], [3], [4]) ) AS pvt
Non ci sono trucchi che si possono fare con SQL dinamico per gestire gruppi di più di tempo variabile e si può anche perno sui nomi sostituendo efficacemente TheGroup con il nome prima del PIVOT.
Altri suggerimenti
Ecco un paio di modi per fare questo in memoria con LINQ.
List<SomeClass> source = new List<SomeClass>()
{
new SomeClass(){ theID = 1, theGroup = 2, theValue="Red"},
new SomeClass(){ theID = 2, theGroup = 2, theValue="Blue"},
new SomeClass(){ theID = 3, theGroup = 2, theValue="Green"},
new SomeClass(){ theID = 1, theGroup = 3, theValue=10},
new SomeClass(){ theID = 2, theGroup = 3, theValue=24},
new SomeClass(){ theID = 3, theGroup = 3, theValue=30},
new SomeClass(){ theID = 1, theGroup = 4, theValue=1},
new SomeClass(){ theID = 2, theGroup = 4, theValue=2},
new SomeClass(){ theID = 3, theGroup = 4, theValue=3}
};
//hierarchical structure
var result1 = source.GroupBy(item => item.theID)
.Select(g => new {
theID = g.Key,
theValues = g
.OrderBy(item => item.theGroup)
.Select(item => item.theValue)
.ToList()
}).ToList();
//holds some names for the next step.
Dictionary<int, string> attributeNames = new Dictionary<int,string>();
attributeNames.Add(2, "CHOICE");
attributeNames.Add(3, "COUNT");
attributeNames.Add(4, "SORT");
//xml structure
var result2 = source
.GroupBy(item => item.theID)
.Select(g => new XElement("Row",
new XAttribute("ID", g.Key),
g.Select(item => new XAttribute(attributeNames[item.theGroup], item.theValue))
));