2

I need to do the following in sql.

table 1:

Year  Client Investment

1999   X     100

1999   Y     200

2000   X     1000

2000   Y     2000

I want to display it in below format for my report:

Client 1999Year   2000Year 

X      100         1000

Any idea how to do the above? I am using sql server 2008

Please help.

4

2 に答える 2

6

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 |
于 2013-03-18T14:20:01.223 に答える
3

これには多くの可能な解決策があります。MAX()1つは、とを使用することですCASE

SELECT  Client,
        MAX(CASE WHEN YEAR = 1999 THEN Investment END) [1999Year],
        MAX(CASE WHEN YEAR = 2000 THEN Investment END) [2000Year]
FROM    TableName
WHERE   Client = 'X'
GROUP   BY Client

またはPIVOT関数を使用する

SELECT Client,
       [1999] AS [1999YEAR],
       [2000] AS [2000YEAR] 
FROM
(
    SELECT  YEAR, CLient, Investment
    FROM    TableName
    WHERE   Client = 'X'
) pvt
PIVOT
(
    MAX(InvestMent)
    FOR YEAR IN ([1999],[2000])
) s
于 2013-03-18T14:19:26.320 に答える