문제

그룹화 ID에 피벗되는 저장 프로 시저 (또는 쿼리 표현)를 작성하려고합니다. 여기와 다른 곳에서 예제를 살펴본 후에는 저장된 절차에서 피벗 진술을 얻지 못했고 도움을 찾고 있습니다.

또한 이것이 나에게 해결책이 될 목록에서 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는 정렬을 의미하므로 그 열의 이름을 지정하고 싶습니다 (이것은 피벗의 단점이지만 괜찮습니다).

ID        CHOICE     COUNT      SORT
1         Red        10     1
2         Blue       24     2
3         Green      30     3
도움이 되었습니까?

해결책

이것은 나를 위해 일했고 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을 사용하여 시간이 지남에 따라 다양한 그룹을 처리하기 위해 할 수있는 트릭이 있으며, 피벗 앞에 이름으로 그룹을 효과적으로 대체하여 이름을 피벗 할 수도 있습니다.

다른 팁

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))
  ));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top