【问题标题】:Unpivoting two separate columns取消旋转两个单独的列
【发布时间】:2021-02-09 04:11:02
【问题描述】:

我正在尝试从表中取消透视多个列。到目前为止,我尝试只使用标准的 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

【问题讨论】:

    标签: sql sql-server stored-procedures unpivot lateral-join


    【解决方案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 的值也拉回来似乎很奇怪。

    【讨论】:

    • 对不起,我忘记了我也需要对新表中的错误作出响应。我已经更新了图片以显示我的意思。对不起。
    【解决方案2】:

    我会推荐cross apply

    select x.*
    from mytable t
    cross appy (values 
        ('e1', e1, e1reason),
        ('e2', e2, e2reason),
        ('e3', e3, e3reason)
    ) x(code, response, reason)
    

    【讨论】:

    • 我忘记了我也需要对新表中的错误作出响应。我更新了图片以显示我的意思。我很抱歉第一次没有正确。非常感谢您的帮助。
    • @Stormfrazier:这是对查询的简单修复。完成。
    猜你喜欢
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    相关资源
    最近更新 更多