SQL Server行到多列

时间:2013-09-06 17:45:11

标签: sql sql-server azure-sql-database

我有以下表格和数据:

CREATE TABLE SourceTbl ([Code] varchar(3), [Total] decimal, [Date] datetime );

INSERT INTO SourceTbl ([Code], [Total], [Date]) 
VALUES ('AA', 100, '2012-12-01'), ('AA', 200, '2013-02-01'), ('BB', 50, '2012-01-01');

简单的选择将返回

Code | Total | Date
'AA' | 100   | 2012-12-01
'AA' | 200   | 2013-02-01
'BB' | 50    | 2012-01-01

但我需要的是以下

Code | Total | Date       | Total | Date
'AA  | 200   | 2013-02-01 | 100   | 2012-12-01
'BB  | 50    | 2012-01-01 | null  | null

我一直在尝试使用PIVOT运算符,但没有成功(基于问题SQL Server Pivot multiple columns based on one column)。

使用该示例,我得到的是两行,其值为空。

总计/日期列可以重复13次,并且必须按日期DESC排序。

SQL小提琴:http://sqlfiddle.com/#!3/f37a1/2

任何帮助表示赞赏! 谢谢!

2 个答案:

答案 0 :(得分:2)

如果您只需要两列:

with cte as (
    select *, row_number() over(partition by Code order by Date) as rn
    from SourceTbl
)
select
    code,
    max(case when rn = 1 then Total end) as Total1,
    max(case when rn = 1 then Date end) as Date1,
    max(case when rn = 2 then Total end) as Total2,
    max(case when rn = 2 then Date end) as Date2
from cte
group by code

=> sql fiddle demo

动态解决方案:

declare @stmt nvarchar(max)

;with cte as (
     select distinct
         cast(row_number() over(partition by Code order by Date) as nvarchar(max)) as rn
     from SourceTbl
)
select @stmt = isnull(@stmt + ', ', '') + 
    'max(case when rn = ' + rn + ' then Total end) as Total' + rn + ',' +
    'max(case when rn = ' + rn + ' then Date end) as Date' + rn 
from cte
order by rn

select @stmt = '
    with cte as (
        select *, row_number() over(partition by Code order by Date) as rn
        from SourceTbl
    )
    select
        code, ' + @stmt + ' from cte group by code'

exec sp_executesql
    @stmt = @stmt

=> sql fiddle demo

答案 1 :(得分:0)

您是否尝试在结果集中动态创建列?

如果您有'AA'的第三条记录,总共300条,并且2013年1月3日的日期意味着你会想要显示这样的内容吗?

Code | Total | Date       | Total | Date      | Total | Date
 AA  | 200   | 2013-02-01 | 100   | 2012-12-01| 300   | 03-01-13
 BB  | 50    | 2012-01-01 | null  | null      | null  | null