【问题标题】:Pivot on multiple aggregated columns透视多个聚合列
【发布时间】:2017-10-25 21:55:03
【问题描述】:

我无法解决以下问题。我的表结构:

ID Type Price Currency
1   A    100    USD
1   B    200    EUR
1   C    300    CAD
2   A    400    EUR
2   B    500    EUR
2   C    600    USD

我需要得到以下结果:

ID   A  A_Currency B    B_Currency  C C_Currency  
 1  100    USD     200    EUR      300    CAD
 2  400    EUR     500    EUR      600    USD  

此时我能够成功地制作没有货币的表格:

select ID, p.A, p.B, p.C from 
(select ID, Price, Type from MyTable) as x
pivot(Max(Price) for Type in 
(A, B, C)) as p

而且效果很好。但现在我真的迷失了如何为每种类型添加货币。我试图将它放在 select 中,但它不起作用,并且 PIVOT 不接受多个列。

【问题讨论】:

    标签: sql sql-server sql-server-2016


    【解决方案1】:

    示例

    Select *
     From (
            Select ID
                  ,B.*
             From  YourTable A
             Cross Apply ( values ( concat(A.Type,'_Currency'),A.Currency)
                                 ,( A.Type,cast(A.Price as varchar(50)))
                         ) B(Item,Value)
          ) A
     Pivot (max(Value) for Item in ([A],[A_Currency],[B],[B_Currency],[C],[C_Currency]) ) p
    

    退货

    ID  A     A_Currency    B     B_Currency    C     C_Currency
    1   100   USD           200   EUR           300   CAD
    2   400   EUR           500   EUR           600   USD
    

    【讨论】:

    • 抱歉回复晚了。这很棒。非常感谢!
    • @user194076 很高兴它有帮助
    猜你喜欢
    • 2016-06-10
    • 1970-01-01
    • 2012-08-12
    • 2020-08-21
    • 2019-06-12
    • 1970-01-01
    • 2013-01-19
    • 2013-03-18
    • 1970-01-01
    相关资源
    最近更新 更多