【问题标题】:Pivot against a SQL stored procedure (or LINQ)以 SQL 存储过程(或 LINQ)为中心
【发布时间】:2009-03-20 16:30:45
【问题描述】:

我正在尝试创建一个以分组 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

【问题讨论】:

    标签: sql linq pivot


    【解决方案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 执行一些技巧来处理随时间变化的组,您还可以通过有效地将 theGroup 替换为 PIVOT 之前的名称来以名称为中心。

    【讨论】:

      【解决方案2】:

      这里有几种使用 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))
        ));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-14
        • 1970-01-01
        • 1970-01-01
        • 2010-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多