0

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

2 回答 2

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 之前的名称来对名称进行透视。

于 2009-03-20T16:47:44.110 回答
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))
  ));
于 2009-03-20T19:00:16.757 回答