想要将行转换为SQL中的列

时间:2019-06-20 13:14:43

标签: sql sql-server

我想将表中的行转换为列。我试图通过下面的查询来处理数据透视表,但是没有运气。

select Percentage, SGST, CGST
from
(
  select 
    * 
  from #Test 
) d
pivot
(
 max(Amount)
 for Name in (SGST, CGST)
) piv

这是我的表结构和查询。

create table #Test(Name varchar(10),Percentage decimal(10,2),Amount decimal(10,2))

insert into #Test values ('SGST',1.5,1008351.12)
insert into #Test values ('SGST',9,3059686.27)
insert into #Test values ('CGST',1.5,1008351.12)
insert into #Test values ('CGST',9,3059686.27)

select * from #Test

Current Out Put :
--------------------------------
Name    SGST    Amount
SGST    1.50    1008351.12
SGST    9.00    3059686.27
CGST    1.50    1008351.12
CGST    9.00    3059686.27

Expected Out Put :
--------------------------------
CGST   CGSTValue     SGST   SGST Value
1.50   1008351.12    1.50   1008351.12
9.00   3059686.27    9.00   3059686.27

预先感谢!

1 个答案:

答案 0 :(得分:3)

您可以通过条件聚合来做到这一点:

select sgst, sum(case when name = 'SGST' then amount end) as sgst_amount,
       sum(case when name = 'CGST' then amount end) as cgst_amount
from test t
group by sgst;