将一列中的值拆分为2列

时间:2013-03-18 14:17:16

标签: sql sql-server database sql-server-2008 pivot

我需要在sql中执行以下操作。

表1:

Year  Client Investment

1999   X     100

1999   Y     200

2000   X     1000

2000   Y     2000

我想以下面的格式显示我的报告:

Client 1999Year   2000Year 

X      100         1000

知道如何做到以上几点? 我正在使用sql server 2008

请帮忙。

2 个答案:

答案 0 :(得分:6)

这种类型的数据转换是a PIVOT。某些数据库产品具有将数据从行转换为列的功能。

您可以在任何数据库中使用带有CASE表达式的聚合函数:

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

请参阅SQL Fiddle with Demo

由于您使用的是SQL Server 2008,因此可以使用PIVOT函数将数据转换为列:

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

请参阅SQL Fiddle with Demo

如果您有一定数量的year值,其他查询将会很有效,但如果您的数字未知,那么您将需要使用动态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)

请参阅SQL Fiddle with Demo

这也可以通过多次加入表格来完成:

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

请参阅SQL Fiddle with Demo

所有查询都会给出结果:

| CLIENT | YEAR_1999 | YEAR_2000 |
----------------------------------
|      X |       100 |      1000 |
|      Y |       200 |      2000 |

答案 1 :(得分:3)

有很多可能的解决方案。一种方法是使用MAX()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