加入数据透视表,重命名列。 SQL

时间:2016-09-12 14:00:54

标签: sql sql-server tsql join pivot

我有以下查询,它从包含日期,货币,mvcleanccy和spotsek的表中进行选择。

问题1.如何将列重命名为DKK,EUR ...到DKK_MV,EUR_MV。

问题2.我有相同的支点,唯一的区别是'MV_SEK' = mvcleanccy*spotsekMV = mvcleanccy取代。 如果我想在查询中的位置日期加入这两个支点,如何在不创建两个单独的表并在之后加入的情况下执行此操作?

SELECT *
FROM(
SELECT 
    currency 
    ,'MV_SEK' = mvcleanccy*spotsek
    ,todaypositiondate
from T1
) as src
PIVOT
(
 sum(MV_SEK)
for
currency in ([DKK], [EUR], [NOK], [SEK], [USD])
)
as pivottable
Order by todaypositiondate desc

2 个答案:

答案 0 :(得分:2)

SELECT currency, [DKK] as [DKK_MV], [EUR] as [EUR_MV], [NOK] as [NOK_MV], [SEK] as [SEK_MV], [USD] as [USD_MV] -- this should rename the columns as per question 1

FROM(
SELECT 
    currency 
    ,'MV_SEK' = mvcleanccy*spotsek
    ,todaypositiondate
from T1
) as src
PIVOT
(
 sum(MV_SEK)
for
currency in ([DKK], [EUR], [NOK], [SEK], [USD])
)
as pivottable
Order by todaypositiondate desc

答案 1 :(得分:1)

我认为使用条件聚合可以简化您的解决方案:

select todaypositiondate,
       sum(case when currency = 'DKK' then mvcleanccy * spotsek end) as dkk_mv,
       sum(case when currency = 'EUR' then mvcleanccy * spotsek end) as eur_mv,
       . . .
       sum(case when currency = 'DKK' then mvcleanccy end) as dkk,
       sum(case when currency = 'EUR' then mvcleanccy end) as eur,
       . . .
from t1
group by todaypositiondate
order by todaypositiondate;