SQL Server 기본 줄 데이터 가 열 데이터 로 변환 됨

5352 단어 sqlserver행 열
준비 작업
생 성 표

use [test1]
go

create table [dbo].[student](
  [id] [int] identity(1,1) not null,
  [name] [nvarchar](50) null,
  [project] [nvarchar](50) null,
  [score] [int] null,
 constraint [pk_student] primary key clustered 
(
  [id] asc
)with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary]
) on [primary]
go
데이터 삽입

insert into test1.dbo.student(name,project,score)
values('  ','android','60'),
   ('  ','ios','70'),
   ('  ','html5','55'),
   ('  ','.net','100'),
   ('  ','android','60'),
   ('  ','ios','75'),
   ('  ','html5','90'),
   ('  ','.net','100');
Case When 과 취 합 함수 로 줄 전용 열 을 진행 합 니 다.
문법

select column_name,
<aggregation function>(<case when expression>) 
from database.schema.table
group by column_name
문법 해석
column_name
데이터 열 이름
aggregation function
취 합 함수,흔히 볼 수 있 는 것 은 sum,max,min,avg,count 등 이 있 습 니 다.
case when expression
case when 표현 식
예시

select name,
max(case project when 'android' then score end) as '  ',
max(case project when 'ios' then score end) as '  ',
max(case project when 'html5' then score end) as 'html5',
max(case project when '.net' then score end) as '.net'
from [test1].[dbo].[student]
group by name
예시 결과
전환 전

전환 후

PIVOT 를 사용 하여 행 전용 열 을 진행 합 니 다.
PIVOT 는 표현 식 의 한 열 에 있 는 유일한 값 을 출력 에 있 는 여러 열 로 변환 하여 표 값 표현 식 을 회전 시 킵 니 다.또한 PIVOT 는 최종 출력 에 필요 한 나머지 열 값 에서 취 합 을 실행 합 니 다.PIVOT 는 일련의 복잡 한 SELECT...CASE 구문 이 지정 한 문법 보다 더 간단 하고 읽 을 수 있 는 문법 을 제공 합 니 다.PIVOT 는 취 합 을 실행 하고 가능 한 여러 줄 을 출력 중의 한 줄 에 합 칩 니 다.
문법

select <non-pivoted column>, 
  [first pivoted column] as <column name>, 
  [second pivoted column] as <column name>, 
  ... 
  [last pivoted column] as <column name> 
from 
  (<select query that produces the data>)  
  as <alias for the source query> 
pivot 
( 
  <aggregation function>(<column being aggregated>) 
for  
[<column that contains the values that will become column headers>]  
  in ( [first pivoted column], [second pivoted column], 
  ... [last pivoted column]) 
) as <alias for the pivot table> 
<optional order by clause>;
문법 해석

비 중합 열.
[first pivoted column]
일렬 로 열거 하 다.
[second pivoted column]
2 열.
[last pivoted column]
마지막 열 이름.

좋은 웹페이지 즐겨찾기