在这里我放置了SQL代码,以便您可以在实例中创建相同的数据:
CREATE TABLE [dbo].[tbl]
(
[CGSTPer] [DECIMAL](18, 2) NULL,
[CGSTAmt] [DECIMAL](18, 2) NULL,
[SGSTPer] [DECIMAL](18, 2) NULL,
[SGSTAmt] [DECIMAL](18, 2) NULL,
[IGSTPer] [DECIMAL](18, 2) NULL,
[IGSTAmt] [DECIMAL](18, 2) NULL,
[Id] [NUMERIC](18, 0) NOT NULL
)
INSERT INTO dbo.tbl
(CGSTPer,CGSTAmt,SGSTPer,SGSTAmt,IGSTPer,IGSTAmt,Id)
SELECT '2.50','35.10','2.50','35.10','0','0',77371
当前数据采用以下格式:
select * from dbo.tbl
CGSTPer CGSTAmt SGSTPer SGSTAmt IGSTPer IGSTAmt Id
2.50 35.10 2.50 35.10 0.00 0.00 77371
我想要如下输出:
id percentage amount type
77371 2.50 35.1 cgst
77371 2.50 35.1 sgst
77371 0 0 igst
答案 0 :(得分:2)
您可以在下面尝试-
select A.id,percentage,amount,types from
(
select id,[percentage],row_number() over(order by id) r from [tbl]
unpivot ([percentage] for N in(CGSTPer,SGSTPer,IGSTPer)) as f1
)A inner join
(
select id,[amount],row_number() over(order by id) r from [tbl]
unpivot ([amount] for N in(CGSTAmt,SGSTAmt,IGSTAmt)) as f2
)B on A.id=B.id and A.r=B.r
inner join
(
SELECT id,types,row_number() over(order by id) r FROM tbl cross apply (VALUES
('cgst'),('sgst'),('igst')
) AS y(types)
)C on A.id=C.id and A.r=C.r
输出:
id percentage amount types
77371 2.50 35.10 cgst
77371 2.50 35.10 sgst
77371 0.00 0.00 igst
答案 1 :(得分:1)
我会使用APPLY
:
select t.id, tt.*
from [dbo].[tbl] t cross apply
( values ('CGST', CGSTPer, CGSTAmt),
('SGST', SGSTPer, SGSTAmt),
('IGST', IGSTPer, IGSTAmt)
) tt(percentage, amount, types);