我有一个不可修改的SQL事务,它返回以下数据:
----------------------
| NAME | VALUE |
----------------------
| Amount | ... |
----------------------
| Target | ... |
----------------------
| Date | ... |
----------------------
| Amount | ... |
----------------------
| Target | ... |
----------------------
| Date | ... |
----------------------
e.g:
我想格式化它,看起来像:
-----------------------------------------
| Amount | Target | Date |
-----------------------------------------
| ... | ... | ... |
-----------------------------------------
我将如何继续完成此操作?
我的代码是:
SELECT
NAME, VALUE
FROM
function(@data)
/* AS PIVOT TABLE(...)*/
我想返回一个格式正确的临时表。
答案 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