/*
drop table #aaa
drop table #bbb
*/
CREATE Table #aaa
(
KeyCol varchar(10),
Section varchar(10)
)
CREATE Table #bbb
(
KeyCol varchar(10),
Name varchar(10),
Score bigint
)
Insert Into #aaa SELECT 'A1001', 'Eng'
Insert Into #aaa SELECT 'A1002', 'Kor'
Insert Into #aaa SELECT 'A1003', 'Cha'
Insert Into #bbb SELECT 'A1001', '신근태', 90
Insert Into #bbb SELECT 'A1001', '우장일', 85
Insert Into #bbb SELECT 'A1001', '정종태', 80
Insert Into #bbb SELECT 'A1002', '신근태', 78
Insert Into #bbb SELECT 'A1002', '우장일', 88
Insert Into #bbb SELECT 'A1002', '정종태', 98
Insert Into #bbb SELECT 'A1003', '신근태', 85
--기본 Left Join
SELECT
A.KeyCol, a.Section, b.Name, b.Score
FROM
#aaa a
LEFT JOIN #bbb b ON a.KeyCol = b.KeyCol
--피벗
SELECT
A.KeyCol, a.Section, b.*
FROM
#aaa a
LEFT JOIN
(
SELECT
KeyCol,
Cast([신근태] As varchar(10)) As [신근태],
Cast([우장일] As varchar(10)) As [우장일],
Cast([정종태] As varchar(10)) As [정종태]
FROM
#bbb
PIVOT
(
MAX(Score)
FOR Name in ([신근태], [우장일], [정종태])
) as PivotTable
) b ON a.KeyCol = b.KeyCol
--XML
SELECT
A.KeyCol, a.Section, c.*
FROM
#aaa a
LEFT JOIN
(
SELECT
Distinct KeyCol,
STUFF((
select ';' + cast(isnull(A.Name, '') as nvarchar(200))
from
(
Select Distinct Name
From #bbb
Where KeyCol = B.KeyCol
) A
FOR XML PATH('')
),1,1,'') As Contents
FROM
#bbb B
) C ON a.KeyCol = c.KeyCol
'DB' 카테고리의 다른 글
(MSSQL) 특정 문자나 숫자 자릿수에 맞춰 0 채우기 (특정문자 채우기) - REPLICATE, RIGHT (0) | 2017.04.13 |
---|---|
(MSSQL) sql 실행 내용 알아내기 - sql profiler 대체 (0) | 2017.04.13 |
(MSSQL) LAG, LEAD, LAST_VALUE, FIRST_VALUE, ROW_NUMBER() OVER() (0) | 2017.04.13 |
(MSSQL) 전체 인덱스 Script 뜨기 (0) | 2017.04.13 |
(MSSQL) sp_ 리스트 (0) | 2017.04.13 |