【问题标题】:SQL Server Rows to Multi-ColumnsSQL Server 行到多列
【发布时间】:2013-09-10 21:32:48
【问题描述】:

我有以下表格和数据:

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

感谢任何帮助! 谢谢!

【问题讨论】:

  • PIVOT + Row_NUMBER() 救援。

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


【解决方案1】:

如果您只需要两列:

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

【讨论】:

  • 很棒的工作!从来不知道你可以动态添加这样的列。
  • 正是我需要的!谢谢!
【解决方案2】:

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

如果您有第三条记录“AA”,总数为 300,日期为 2013 年 3 月 1 日,您是否意味着您希望显示这样的内容?

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        

【讨论】:

  • 这应该是评论而不是回答
  • 是的,我最多可以有 13 个总计/日期组合。
猜你喜欢
  • 1970-01-01
  • 2013-08-04
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多