SQL Server - 转置表并以正确的格式返回临时表

时间:2017-12-05 16:49:38

标签: sql-server sql-server-2012 transpose

我有一个不可修改的SQL事务,它返回以下数据:

----------------------
| NAME    |   VALUE  |
----------------------
| Amount   |    ...  |
----------------------
| Target   |    ...  |
----------------------
| Date     |    ...  |
----------------------
| Amount   |    ...  |
----------------------
| Target   |    ...  |
----------------------
| Date     |    ...  |
----------------------

e.g:

enter image description here

我想格式化它,看起来像:

-----------------------------------------
|   Amount    |   Target    |   Date    |
-----------------------------------------
|    ...      |    ...      |   ...     |
-----------------------------------------

我将如何继续完成此操作?

我的代码是:

SELECT 
NAME, VALUE
FROM
function(@data)
/* AS PIVOT TABLE(...)*/

我想返回一个格式正确的临时表。

1 个答案:

答案 0 :(得分:2)

尝试使用select并将#foo替换为您的记录源,并忽略所有设置,除非您只想运行此特定示例。

分组基于位置,您可以使用floor((row_number()over(order by(select 1)) - 1)/ 3)来获取每三行的一组。

create table #foo (
Name varchar(50),
StringValue varchar(50))


insert into #foo values ('Amount', '200')
insert into #foo values ('Target', '66')
insert into #foo values ('Date', '2017-1-1')
insert into #foo values ('Amount', '205')
insert into #foo values ('Target', '67')
insert into #foo values ('Date', '2017-3-1')


select 
    max(case when Name = 'Amount' then StringValue else null end) as Amount, 
    max(case when Name = 'Target' then StringValue else null end) as Target, 
    max(case when Name = 'Date' then StringValue else null end) as Date
from (
    select floor((row_number() over (order by (select 1)) - 1) / 3) as group_on, * from #foo 
    ) temp
group by group_on

drop table #foo