对SQL存储过程(或LINQ)进行透视

时间:2009-03-20 16:30:45

标签: sql linq pivot

我正在尝试创建一个在分组ID上进行隐藏的存储过程(或查询表达式)。在查看此处和其他地方的示例之后,我无法将我的数据透视语句用于存储过程,我正在寻求帮助。

另外,如果可以在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表示CHOICE,组#3表示COUNT,组#4表示SORT,所以我想命名那些列(我意识到这是PIVOT的缺点,但没关系)。

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

2 个答案:

答案 0 :(得分: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之前用名称有效地替换Group来转移名称。

答案 1 :(得分: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))
  ));