我需要将多个列转置为一个特定的列SQL(我的实际示例具有多个列和行)。请查看图片以了解到目前为止的详细信息。我还附上了我创建的临时表的完整代码。
我试图单独解决该问题,并创建了两个查询:
我不知道如何将查询#堆栈中新创建的“ columns”列下的所有数据相加,并且不确定是否可能。
----created new tables : test and plan test
create table test (
plancode int,
amount int,
category varchar (255),
ownership varchar (255),
status varchar (255))
select * from test
insert into test (
plancode,
amount,
category,
ownership,
status)
values (5,100,'parttime','simple', 'inprogress')
insert into test (
plancode,
amount,
category,
ownership,
status)
values (5,100,'fulltime','simple', 'inprogress')
insert into test (
plancode,
amount,
category,
ownership,
status)
values (10,100,'fulltime','simple', 'inprogress')
insert into test (
plancode,
amount,
category,
ownership,
status)
values (10,10,'partime','partial', 'complete')
insert into test (
plancode,
amount,
category,
ownership,
status)
values (15,100,'seasonal','full', 'complete')
insert into test (
plancode,
amount,
category,
ownership,
status)
values (15,200,'partime','simple','complete')
create table plantest (
plancode int,
planname varchar (255))
insert into plantest (
plancode,
planname)
values (5, 'plan A')
insert into plantest (
plancode,
planname)
values (10, 'plan B')
insert into plantest (
plancode,
planname)
values (15, 'plan C')
-----------------------------------------------------------------------------
Temp tables are created below
select * from test
select * from plantest
________________________________________________________________
This #1 query is for union all.
select plancode,
category as columns from test
union all
select plancode, ownership from test
union all
select plancode, status from test
此#2查询用于全部透视。
---pivoting on one of the columns, 'category' but I need to include all the other columns 'ownership' and 'status' right under the last value of 'category' column in this query
select * from (
select
category, ---only including one column.. that is why I thought if I stack all data under values here that it should work but right now it is not stacked.
amount,
plancode
from test) as tbl
pivot (sum(amount) for plancode in ([5],[15],[10])) as pivottable