2009-03-20 14 views
0

グループ化IDでピボットするストアドプロシージャ(またはクエリ式)を作成しようとしています。ここや他の例を見ると、私のピボットステートメントがストアドプロシージャで動作するのに失敗し、私は助けを探しています。SQLストアドプロシージャ(またはLINQ)に対するピボット

また、LISTの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はグループ#3は、COUNT、グループ#4は、SORTので、私は(私はこれはPIVOTの欠点で実現するが、それはOKです)、それらの列を名前を付けたいことを意味し、CHOICEを意味します。

ID  CHOICE  COUNT  SORT 
1   Red  10  1 
2   Blue  24  2 
3   Green  30  3 

答えて

1

これは私のために働いたと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の前の名前に置き換えます。

+0

ありがとう、それは美しく働いた! –

1

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)) 
)); 
関連する問題