SQLストアドプロシージャ(またはLINQ)に対してピボット
質問
私はグループIDに旋回するストアド・プロシージャ(またはクエリ式)を作成しようとしています。ここでは、他の場所の例を見た後、私は、ストアドプロシージャで動作するように私のピボット文を取得するために失敗している、と私は私の助けを探しています。
また、これも私のための解決策になるリストにLINQで行うことができれば。
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
グループ#2は、CHOICEを意味し、グループ#3は、COUNT、グループ#4は、SORTので、私は(私はこれはPIVOTの欠点で実現するが、それはOKです)、それらの列を名前を付けたい。
意味意味しますID CHOICE COUNT SORT
1 Red 10 1
2 Blue 24 2
3 Green 30 3
解決
これは私のために働いたと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
あなたが時間をかけて様々なグループを処理するために、動的SQLで行うことができますし、また効果的PIVOT前に名前とtheGroupを置き換えることによって、名前の上に旋回することができるトリックがあります。
他のヒント
ここで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))
));
所属していません StackOverflow