반응형
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
반응형
'프로그래밍 > DataBase' 카테고리의 다른 글
[MS-SQL] 암호화 PWDENCRYPT, PWDCOMPARE (0) | 2022.05.26 |
---|---|
[MSSQL] JSON_MODIFY (0) | 2022.03.24 |
데이터 리터러시( Data literacy ) (0) | 2022.02.23 |
[MSSQL] 특정 기간에 해당하는 모든 날짜 (MASTER..SPT_VALUES) (0) | 2022.02.23 |
[MSSQL] Adding string to DATEDIFF(day,getdate(),enddate) as DayRemain how please? (0) | 2022.02.21 |