如何将行数据用作具有可变行数据的列

时间:2014-05-23 12:08:10

标签: sql sql-server-2008

我在数据库中有一个表:

enter image description here

我希望数据输出如下:

enter image description here

FeeName列值不固定,也可以是其他类型的费用。

请帮助解决它。

寻找有价值的解决方案。

...谢谢

2 个答案:

答案 0 :(得分:3)

正如Turophile所说,这种数据格式表明您的数据设计存在问题。

尽管如此,如果你需要这样做,我也会这样做:

(注意我创建了一个临时表,并在示例中填充了它。你已经拥有了表和数据,但我需要一些东西进行测试)

Create table #feeSchedule
(
    FeeId int identity(1,1) not null primary key,
    Description nvarchar(255) not null,
    FeeAmount money not null,
    FeeName nvarchar(50) not null
)
go

insert into #feeSchedule values('Nursery', 5000, 'Admission Fee')
insert into #feeSchedule values('Nursery', 1000, 'Tuition Fee')
insert into #feeSchedule values('Nursery', 100, 'Late Fee')
insert into #feeSchedule values('Nursery', 0, 'Exam Fee')
insert into #feeSchedule values('Play Group', 5000, 'Admission Fee')
insert into #feeSchedule values('Play Group', 2500, 'Tuition Fee')
insert into #feeSchedule values('Play Group', 100, 'Late Fee')
insert into #feeSchedule values('Play Group', 0, 'Exam Fee')


DECLARE @columnHeaders VARCHAR(MAX)
SELECT @columnHeaders = 
  COALESCE( 
    @columnHeaders + ',[' + cast(FeeName as varchar) + ']',
    '[' + cast(FeeName as varchar)+ ']'
  )
FROM (select distinct FeeName from #feeSchedule) as fs

DECLARE @sql NVARCHAR(MAX)
SET @sql = N'
  SELECT *
  FROM (
    SELECT
      fs.Description,
      fs.FeeName,
      fs.FeeAmount
    FROM #feeSchedule fs
  ) AS PivotData
  PIVOT (
    SUM(FeeAmount)
    FOR FeeName IN (
      ' + @columnHeaders + '
    )
  ) AS PivotTable
'

exec sp_ExecuteSql @sql

go
drop table #feeSchedule

答案 1 :(得分:0)


SELECT *
FROM (
SELECT 
    Description(invoiceDate) as [year],FeeAmount, 
    InvoiceAmount as Amount 
FROM TableName
) as s
PIVOT
(
SUM(Amount)
FOR [month] IN (Admission Fee, Tution Fee, Exam Fee, Late Fee)
)AS pivot