This type of data transformation is known an a PIVOT
. Some database products have a function that will turn the data from rows to columns.
You can use an aggregate function with a CASE
expression in any database:
select client,
sum(case when year = 1999 then investment end) Year_1999,
sum(case when year = 2000 then investment end) Year_2000
from yourtable
group by client
See SQL Fiddle with Demo
Since you are using SQL Server 2008, you can use the PIVOT
function to transform the data into columns:
select *
from
(
select client,
'Year_'+cast(year as varchar(4)) year,
investment
from yourtable
) src
pivot
(
sum(investment)
for year in (Year_1999, Year_2000)
) piv
See SQL Fiddle with Demo.
The other queries will work great if you have a known number of year
values, but if you have an unknown number, then you will want to use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME('Year_'+cast(year as varchar(4)))
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT client,' + @cols + ' from
(
select client,
''Year_''+cast(year as varchar(4)) year,
investment
from yourtable
) x
pivot
(
sum(investment)
for year in (' + @cols + ')
) p '
execute(@query)
See SQL Fiddle with Demo.
This can also be done by joining on the table multiple times:
select t1.client,
t1.investment Year_1999,
t2.investment Year_2000
from yourtable t1
left join yourtable t2
on t1.client = t2.client
and t2.year = 2000
where t1.year = 1999
See SQL Fiddle with Demo
All queries give the result:
| CLIENT | YEAR_1999 | YEAR_2000 |
----------------------------------
| X | 100 | 1000 |
| Y | 200 | 2000 |