2016-09-12 2 views
0

Ich habe unter Abfrage, die aus einer Tabelle mit Datum, Währung, mvcleanccy und spotsek auswählt.Pivot-Tabellen verbinden, Spalten umbenennen. SQL

Frage 1. Wie benenne ich die Spalten so von DKK, EUR ... zu DKK_MV, EUR_MV um.

Frage 2. Ich habe den gleichen Drehpunkt mit dem einzigen Unterschied, dass 'MV_SEK' = mvcleanccy*spotsek durch MV = mvcleanccy ersetzt wird. Wenn ich diese zwei Pivots am Positionsdatum in der Abfrage verbinden möchte, wie mache ich das, ohne zwei separate Tabellen zu erstellen und danach zu verbinden?

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

Frage 2 völlig unklar –

+0

ist ich jetzt umformuliert. – Haggan

+0

Welches DBMS benutzen Sie? Ihre Abfrage ist Nicht-Standard-SQL. –

Antwort

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

Ich denke, Ihre Lösung mit bedingter Aggregation einfacher wäre:

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

Vielen Dank! Viel besser. – Haggan

Verwandte Themen