我正在使用SQL Server 2014.我有一个这样的表:
MONTH BILL AMOUNT PAID AMOUNT
Jan 2937.00 2940.00
Dec 2938.00 2940.00
Nov 0.00 0.00
Oct 2940.00 2940.00
Sep 2935.00 2940.00
Aug 2936.00 2940.00
我想要这样的输出:
前6个月的比尔详情
Month Jan Dec Nov Oct Sep Aug
Bill Amount 2937.00 2938.00 0 2940.00 2935.00 2936.00
Paid Amount 2940.00 2940.00 0 2940.00 2940.00 2940.00
有人可以建议解决方案吗?
答案 0 :(得分:0)
我尝试过使用SQL Server 2008。 指定的月份静态列名称。
select name as [MONTH], [Jan], [Dec], [Nov], [Oct], [Sep], [Aug]
from
(
select [MONTH], name, value
from testtable
unpivot
(
value for name in (BILLAMOUNT, PAIDAMOUNT)
) unpiv
) src
pivot
(
sum(value)
for [MONTH] in ([Jan], [Dec], [Nov], [Oct], [Sep], [Aug])
) piv
当需要动态列月份时: -
DECLARE @colsUnpivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX),
@colsPivot as NVARCHAR(MAX)
select @colsUnpivot = stuff((select ','+quotename(C.name)
from sys.columns as C
where C.object_id = object_id('test2') and
C.name <> 'MONTH'
for xml path('')), 1, 1, '')
select @colsPivot = STUFF((SELECT ','
+ quotename([MONTH])
from testtable t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'select name as [MONTH], '+@colsPivot+'
from
(
select [MONTH], name, value
from testtable
unpivot
(
value for name in ('+@colsUnpivot+')
) unpiv
) src
pivot
(
sum(value)
for [MONTH] in ('+@colsPivot+')
) piv'
exec(@query)
答案 1 :(得分:0)
你可以试试这个,
Create table #billing
(
[MONTH] varchar(15),
[BILL_AMOUNT] Decimal(8,2),
[PAID_AMOUNT] Decimal(8,2)
)
Insert Into #billing
Values('Jan', 2937.00, 2940.00),
('Dec', 2938.00, 2940.00),
('Nov', 0.00 , 0.00 ),
('Oct', 2940.00, 2940.00),
('Sep', 2935.00, 2940.00),
('Aug', 2936.00, 2940.00)
SELECT MONTH,BILL_AMOUNT,PAID_AMOUNT FROM #billing
SELECT 'Bill Amount'as Month,Jan,Dec,Nov,Oct,Sep,Aug
FROM (
SELECT BILL_AMOUNT,MONTH
FROM #billing
) AS source_table
PIVOT
(
SUM(BILL_AMOUNT)
FOR MONTH
in(Jan,Dec,Nov,Oct,Sep,Aug)
)AS Pivot_table
Union all
SELECT 'Paid Amount'as Month,Jan,Dec,Nov,Oct,Sep,Aug
FROM (
SELECT PAID_AMOUNT,MONTH
FROM #billing
) AS source_table
PIVOT
(
SUM(PAID_AMOUNT)
FOR MONTH
in(Jan,Dec,Nov,Oct,Sep,Aug)
)AS Pivot_table