declare @Funds table
(
country varchar(20),
[2002] int,
[2006] int,
[2010] int,
[2014] int
);
insert into @Funds(country, [2002], [2006], [2010], [2014])
values ('Chicago', 1000, 23000, 4500, 9076);
declare @Medals table
(
year int,
sport varchar(20),
event varchar(20),
country varchar(20),
gender char(1),
medal_rank tinyint,
medal varchar(20)
);
insert into @Medals(year, sport, event, country, gender, medal_rank, medal)
values
(2006, 'A', 'Z', 'Chicago', 'F', 2, 'silver'),
(1924, 'B', 'ZZ', 'Newyork', 'M', 3, 'bronze'),
(2014, 'C', 'ZZZZ', 'Chicago', 'M', 1, 'Gold'),
(1967, 'B', 'ZZb', 'Newyork', 'M', 3, 'bronze'),
(2014, 'C', 'ZZa', 'Chicago', 'F', 2, 'silver');
select
S.country,
S.Yr,
qu.year /*??*/,
s.value,
count(qu.medal) as countofmedals,
cast(isnull(s.value*1./nullif(count(qu.medal), 0), 0) as decimal(19,2)) as [value/medal]
from
(
select
country,
yr,
value
from @Funds
unpivot
(
value for yr in ([2002],[2006],[2010],[2014]) --!!!!
) as u
) s
left join @medals qu --!!!!
on (s.country=qu.country and s.Yr=qu.year)
group by s.country, s.Yr,qu.year/*??*/,s.value;