在sql中如何使用Pivot将数据行排列到列中

时间:2017-04-25 07:16:18

标签: sql sql-server tsql pivot

这里我有一个简单的表格,我希望显示当年显示在单列

中的所有行
Year  Month     Amt
1999   Jan       520
1999   Feb       100
199    Mar       200
2000   Jan       500
2000   Feb        200

我想将这些表显示为

Year   Jan     Feb     Mar   
1999    520    100      200  
2000    500    200      null

我的书面查询为invoice我的表名

   select
       [Jan] as January,
       [Feb] as Feburary,
       [March] as Feburary,
from(
select Year,month,amount from invoice)x

PIVOT(
sum(amount)
for month in([jan],[Feb],[March])

)p

2 个答案:

答案 0 :(得分:1)

请尝试此查询

create table #Invoice
(
    ID int identity(1,1),
    Year varchar(4),
    Month varchar(3),
    Amount int
)

insert into #Invoice (Year, Month, Amount) values ('1999','Jan',520),('1999','Feb',100),('1999','Mar',200),
('2000','Jan',500),('2000','Feb',200)

select Year, [Jan], [Feb],[Mar],[Grand Total]
from (
    select Year, Month, Amount
    from #Invoice
    Union all
    select Year, 'Grand Total', SUM(Amount)
    from #Invoice
    group by year
)dd
pivot (
    sum(Amount) for Month in ([Jan], [Feb],[Mar],[Grand Total])
) piv

drop table #Invoice

enter image description here

答案 1 :(得分:0)

您可以使用CTE来实现它。您不能在PIVOT表运算符中进行GROUP BY YEARPIVOT运算符会自动推断分组列。这似乎有效

WITH Pivoted
AS
(
SELECT *
FROM table1
PIVOT 
( 
sum([Amt]) FOR [month] IN ( [jan],[Feb],[Mar])
) AS p
) 
SELECT 
    Year,
    sum([Jan]) as January,
    sum([Feb]) as Feburary,
    sum([Mar]) as March
FROM Pivoted
GROUP BY Year;

REXTESTER DEMO