2016-09-12 28 views
0

我有下面的查詢,它從包含日期,貨幣,mvcleanccy和spotsek的表中進行選擇。連接數據透視表,重命名列。 SQL

問題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 
+3

問題2是完全 –

+0

不清楚我現在轉述。 – Haggan

+0

您正在使用哪些DBMS?您的查詢是非標準的SQL。 –

回答

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

我認爲您的解決方案將符合條件的聚集簡單:

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; 
+0

謝謝!好多了。 – Haggan