简体   繁体   English

计算 UNPIVOT 中两列之间的差异

[英]Calculating a difference between two columns within an UNPIVOT

I am trying to perform an UNPIVOT, but one of my columns was actually the difference between two columns, and SSMS is not accepting that as one of the values in the creation of the un-pivoted field.我正在尝试执行 UNPIVOT,但我的一列实际上是两列之间的差异,并且 SSMS 不接受将其作为创建非透视字段的值之一。

Example:例子:

UNPIVOT(                                                                                                 
        Points
        for PointType in (                                                                                   
                          HomeTeamPoints
                        , (HomeTeamPoints - TotalPoints)
                        , TotalPoints

        ) as pnts

This works perfectly if I comment out the difference field, but once that's in it tells me "incorrect syntax near '('". Once i remove the parentheses it says "Incorrect Syntax near '-'"如果我注释掉差异字段,这非常有效,但是一旦它告诉我“'('附近的语法不正确”。一旦我删除括号,它就会说“'-'附近的语法不正确”

Anyone know if there's a way to make this go through?任何人都知道是否有办法让这个 go 通过?

Thanks a lot非常感谢

Don't use unpivot .不要使用unpivot Use apply :使用apply

select v.*
from t cross apply
     (values ('HomeTeamPoints', HomeTeamPoints),
             ('Diff', HomeTeamPoints - TotalPoints),
             ('TotalPoints', TotalPoints)
     ) v(which, points);

unpivot is bespoke syntax that does only one thing. unpivot是只做一件事的定制语法。 apply implements lateral join s. apply实现横向连接 These are very powerful types of joins and are part of the standard.这些是非常强大的连接类型,并且是标准的一部分。 Unpivoting is only the beginning of what you can do with apply . Unpivoting 只是您可以使用apply做的事情的开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM