1

我有下表和数据:

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问题)。

使用该示例,我得到的只是两行具有空值的行。

Total/Date 列可以重复 13 次,它们必须按 Date DESC 排序。

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

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

4

2 回答 2

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 小提琴演示

动态解决方案:

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 小提琴演示

于 2013-09-06T18:40:03.297 回答
0

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

如果您有第三条记录“AA”,总共有 300 条记录,日期为 03/01/2013,这是否意味着您想要显示这样的内容?

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        
于 2013-09-06T18:21:53.527 回答