2017-03-21 1 views
1

나는 다음 표를 따릅니다대로 :SQL 서버에서 피벗을 사용하여 열을 행으로 변환

enter image description here

나는 다음과 같이 변환 하시겠습니까 :

어떤 도움
+------------+---------------------+---------------------+ 
| Child_Code |  SewingStart  |  SewingEnd  | 
+------------+---------------------+---------------------+ 
|  000001 | 2017-02-21 00:00:00 | 2017-03-21 00:00:00 | 
+------------+---------------------+---------------------+ 

하세요 !! !!

+3

점유율 % SQL Server에서 'Pivot'을 사용하여 [행을 열로 변환] 복제본 (http://stackoverflow.com/questions/15931607/convert-rows-to-columns-using-pivot-in-sql-server) –

+0

일부 추가 더 많은 샘플 데이터를 사용하면 더 까다 롭고 자세한 설명이 가능합니다. (코드 당 항상 두 개의 날짜가있는 경우 그룹 단위로 작업 할 수 있습니다.) – jarlh

답변

2

제한된 행 수가있는 경우 조건부 집계 또는 피벗을 사용할 수 있습니다. 그러나 이것을 위해 칼럼이 필요합니다. 따라서 :

select child_code, 
     max(case when seqnum = 1 then plan_date end) as plan_date_1, 
     max(case when seqnum = 2 then plan_date end) as plan_date_2 
from (select t.*, 
      row_number() over (partition by child_code order by plan_date) as seqnum 
     from t 
    ) t 
group by child_code; 

최대 계획 날짜 수를 알고있는 경우에만이 방법을 사용할 수 있습니다. 그렇지 않으면 동적 피벗을 사용해야합니다. 아이디어는 동일하지만 쿼리 문자열을 구성해야하며 sp_executesql으로 전달해야합니다.

는 편집 :

당신은 단지 두 개의 값을 가지고 있다면, group by 아마 쉽다. 다음은 하나 개의 값이 사건을 처리합니다

select child_code, min(plan_date) as plan_date_1, 
     (case when min(plan_date) <> max(plan_date) then max(plan_date) 
     end) as plan_date_2 
from t 
group by child_code; 
+0

와우! 그것은 작동! 문제 없어! plan_date는 2로 제한됩니다! 친애하는 Gordon Linoff, 나는 너에게 좀 더 도움이 필요해 !! 잠깐 내가 여기서 너를 언급 할거야. 너는 나를 도울거야. – TanvirArjel

1

당신은 plan_date의 최대 수를 알 수없는 경우 동적 SQL을 사용해야합니다. pivot()과 함께 사용하기 위해 Child_Code으로 분할 된 각 목록의 번호를 지정하려면 row_number()을 사용해야합니다.

테스트 설정 :

create table t (child_code varchar(6), plan_date datetime); 
insert into t values ('000001','20170221'),('000001','20170321'); 
declare @cols nvarchar(max); 
declare @sql nvarchar(max); 

    select @cols = stuff((
    select distinct 
     ',' + quotename('Plan_Date_' 
      +convert(nvarchar(10),row_number() over (
       partition by Child_Code 
       order by  Plan_Date 
     )) 
     ) 
     from t 
     for xml path (''), type).value('.','nvarchar(max)') 
    ,1,1,''); 

select @sql = ' 
select Child_Code, ' + @cols + ' 
from (
    select 
     Child_Code 
    , Plan_Date 
    , rn=''Plan_Date_''+convert(nvarchar(10),row_number() over (
      partition by Child_Code 
      order by  Plan_Date 
     )) 
    from t 
    ) as a 
pivot (max([Plan_Date]) for [rn] in (' + @cols + ')) p'; 
select @sql as CodeGenerated; 
exec sp_executesql @sql; 

rextester 데모 : http://rextester.com/YQCR87525

코드가 생성 :

select Child_Code, [Plan_Date_1],[Plan_Date_2] 
from (
    select 
     Child_Code 
    , Plan_Date 
    , rn='Plan_Date_'+convert(nvarchar(10),row_number() over (
      partition by Child_Code 
      order by  Plan_Date 
     )) 
    from t 
    ) as a 
pivot (max([Plan_Date]) for [rn] in ([Plan_Date_1],[Plan_Date_2])) p 

반환

+------------+---------------------+---------------------+ 
| Child_Code |  Plan_Date_1  |  Plan_Date_2  | 
+------------+---------------------+---------------------+ 
|  000001 | 21.02.2017 00:00:00 | 21.03.2017 00:00:00 | 
+------------+---------------------+---------------------+ 
+0

답해 주셔서 감사합니다 !! 그것은 또한 나를 위해 작동합니다! – TanvirArjel

+0

@TanvirArjel 도와 드리겠습니다! – SqlZim

+0

다시 내 질문을 참조하십시오. 나는 Plan_Date_1을 SewingStart로 대체하고 Plan_Date_2를 SewingEnd로 대체하여 일부를 확장했습니다! – TanvirArjel

관련 문제