代码之家  ›  专栏  ›  技术社区  ›  Ash Machine

根据SQL存储过程(或LINQ)透视

  •  0
  • Ash Machine  · 技术社区  · 16 年前

    我正在尝试创建一个以分组ID为轴心的存储过程(或查询表达式)。在查看了这里和其他地方的示例后,我未能使PIVOT语句在存储过程中工作,我正在寻求帮助。

    另外,如果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表示计数,组4表示排序,因此我想命名这些列(我知道这是Pivot的缺点,但没关系)。

    ID        CHOICE     COUNT      SORT
    1         Red        10     1
    2         Blue       24     2
    3         Green      30     3
    
    2 回复  |  直到 16 年前
        1
  •  1
  •   Cade Roux    16 年前

    这对我很有用,应该在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来处理随时间变化的组,还可以通过有效地将组替换为透视前的名称来透视名称。

        2
  •  1
  •   Amy B    16 年前

    下面是用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))
      ));