当前位置:  开发笔记 > 数据库 > 正文

Calculating a difference between two columns within an UNPIVOT

如何解决《CalculatingadifferencebetweentwocolumnswithinanUNPIVOT》经验,为你挑选了1个好方法。

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.

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?

Thanks a lot



1> Gordon Linof..:

Don't use unpivot. Use 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. apply implements lateral joins. 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.

推荐阅读
郑小蒜9299_941611_G
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有