반응형

PIVOT SUM FOR IN PIVOT_TABLE

 

PIVOT을 이용하여 세로를 가로로 변환 방법(행 열 변환) 

SELECT Student  
, isnull(CAST([Mathematics] AS varchar), '' ) [Mathematics]
, isnull(CAST([Science] AS varchar), '' ) [Science]
, isnull(CAST([Geography] AS varchar), '' ) [Geography]
-- , * 
FROM (
  SELECT
    [Student],
    [Subject],
    [Marks]
  FROM #TEMP_TABLE_Grades
) StudentResults
PIVOT (
  SUM([Marks])
  FOR [Subject]
  IN (
    [Mathematics],
    [Science],
    [Geography]
  )
) AS PivotTable;

IF OBJECT_ID('tempdb..#TEMP_TABLE_Grades') --임시 테이블 남아있을시 삭제 
  IS NOT NULL DROP TABLE #TEMP_TABLE_Grades;
 

CREATE TABLE #TEMP_TABLE_Grades(
  [Student] VARCHAR(50),
  [Subject] VARCHAR(50),
  [Marks]   INT
);
 
INSERT INTO #TEMP_TABLE_Grades VALUES 
('Jacob','Mathematics',100),
('Jacob','Science',95),
('Jacob','Geography',90),
('Jacob2','Mathematics',''),
('Jacob2','Science',''),
('Amilee','Mathematics',90),
('Amilee','Science',90),
('Amilee','Geography',100);
 
SELECT * FROM (
  SELECT
    [Student],
    [Subject],
    [Marks]
  FROM #TEMP_TABLE_Grades
) StudentResults
PIVOT (
  SUM([Marks])
  FOR [Subject]
  IN (
    [Mathematics],
    [Science],
    [Geography]
  )
) AS PivotTable
반응형

+ Recent posts