0

我正在尝试从表中取消透视多个列。到目前为止,我尝试只使用标准的 Unpivot,它在第一部分是成功的,但不是第二部分。我想要两列 Unpivote。我附上了一张我正在尝试做的事情的图片。该表与错误有关。所以E1是error1的缩写,E2是error2的缩写等等......

INSERT INTO #tempWorkflowItem
SELECT AssignmentId, Code, Response FROM #temp2
UNPIVOT(Response FOR Code in (E1, E2, E3 ))AS WorkflowItemsUnpivot
UNPIVOT(Reason FOR Code in (E1Reason, E2Reason, E3Reason )) AS WorkflowItemsUnpivot2

表格转换

4

2 回答 2

1

使用apply

select v.code, v.reason
from #temp2 t cross apply
     (values ('E1', E1Reason), 
             ('E2', E2Reason), 
             ('E3', E3Reason)
     ) v(code, reason, e1, e2, de3);

我怀疑你还想要一个where子句:

where v.code = 'E1' and t.e1 > 0 and
      v.code = 'E2' and t.e2 > 0 and
      v.code = 'E3' and t.e3 > 0 ;

或者:

where v.reason is not null

NULL将价值观也拉回来似乎很奇怪。

于 2020-10-26T21:14:59.727 回答
1

我会推荐cross apply

select x.*
from mytable t
cross appy (values 
    ('e1', e1, e1reason),
    ('e2', e2, e2reason),
    ('e3', e3, e3reason)
) x(code, response, reason)
于 2020-10-26T21:15:36.110 回答