SQL Server行到多列
我有以下表格和数据:SQL Server行到多列,sql,sql-server,azure-sql-database,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 | Tota
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操作符来实现这一点,但没有成功(基于这个问题)
使用该示例,我得到的只是两行空值
“总计/日期”列可以重复13次,并且必须按日期说明排序
SQL Fiddle:
感谢您的帮助!
谢谢 是否尝试在结果集中动态创建列 如果您有第三条“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
如果只需要两列:
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
动态解决方案:
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
为营救提供支点
+行号()
。这应该是一个注释而不是答案是的,我最多可以有13个总/日期组合。干得好!我从来不知道你可以动态添加这样的列。这正是我所需要的!非常感谢。