SQL에서는 행과 열을 교환해야 하는 경우가 많습니다. PIVOT은 적합한 도구처럼 보이지만 지나치게 복잡해 보이는 상황이 있습니다. 다행히도 이 변환을 수행할 수 있는 몇 가지 더 쉬운 대안이 있습니다.
PIVOT이 어려워 보인다면 집계 함수 및 CASE 문과 결합된 UNION ALL을 사용하여 해당 기능을 복제할 수 있습니다.
select name, sum(case when color = 'Red' then value else 0 end) Red, sum(case when color = 'Green' then value else 0 end) Green, sum(case when color = 'Blue' then value else 0 end) Blue from ( select color, Paul value, 'Paul' name from yourTable union all select color, John value, 'John' name from yourTable union all select color, Tim value, 'Tim' name from yourTable union all select color, Eric value, 'Eric' name from yourTable ) src group by name
변환하려는 특정 열과 색상을 알고 있는 경우 정적 실행을 위해 하드코딩할 수 있습니다.
select name, [Red], [Green], [Blue] from ( select color, name, value from yourtable unpivot ( value for name in (Paul, John, Tim, Eric) ) unpiv ) src pivot ( sum(value) for color in ([Red], [Green], [Blue]) ) piv
열 수와 색상을 알 수 없는 경우 동적 SQL을 사용하여 필요한 목록을 생성할 수 있습니다.
DECLARE @colsUnpivot AS NVARCHAR(MAX), @query AS NVARCHAR(MAX), @colsPivot as NVARCHAR(MAX) select @colsUnpivot = stuff((select ','+quotename(C.name) from sys.columns as C where C.object_id = object_id('yourtable') and C.name <> 'color' for xml path('')), 1, 1, '') select @colsPivot = STUFF((SELECT ',' + quotename(color) from yourtable t FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = 'select name, '+@colsPivot+' from ( select color, name, value from yourtable unpivot ( value for name in ('+@colsUnpivot+') ) unpiv ) src pivot ( sum(value) for color in ('+@colsPivot+') ) piv' exec(@query)
어떤 방법을 선택하든 결과는 같습니다.
| 에릭 3 | 5 |
| 5 | 2 |
| 폴 | 1 | 2 |
| 1 | 9 |
위 내용은 SQL에서 열과 행을 쉽게 전치하려면 어떻게 해야 합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!