Mam do rozwiązania następującą łamigłówkę (a dokładniej pilne zadanie biznesowe) SQL SERVER 2008
Mam tabelę tego formularza
ID Market SubMarket Value
1 1 1 3
2 1 2 6
3 1 3 2
4 2 23 1
5 2 24 9
Mam określone identyfikatory rynku i wszystkie identyfikatory rynku mająkonkretne SubMarketID (maksymalnie 5 - wiem, jak to zrobić dla każdego) np. MarketID 1 ma SubMarketIDs 1,2,3 MarketID 2 ma SubMarketID 23,24 itd a każdy SubMarketID ma wartość zmiennej
Muszę przekształcić swoje dane w stałą tabelę tego typu
MarketID SubMarketAvalue SubMarketBValue SubMarketCValue....SubMarketEValue
1 3 6 2 null
2 1 9 null null
SubMarketAValue musi zawierać wartość mniejszego SubMarketID
SubMarketBValue musi zawierać wartość następnego większego SubMarketID
Jakieś eleganckie pomysły? :)
Z góry z góry!
Odpowiedzi:
2 dla odpowiedzi № 1Nie określono RDBMS, ale można użyć następujących opcji w SQL Server 2005+, Oracle i PostgreSQL:
select market,
max(case when rn = 1 then value end) as SubMarketAvalue,
max(case when rn = 2 then value end) as SubMarketBvalue,
max(case when rn = 3 then value end) as SubMarketCvalue,
max(case when rn = 4 then value end) as SubMarketDvalue,
max(case when rn = 5 then value end) as SubMarketEvalue
from
(
select id, market, submarket, value,
row_number() over(partition by market
order by market, submarket) rn
from yourtable
) x
group by market