Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

sql server 2008 - T-SQL Pivot/Unpivot(Transpose) Column Headers Needed as Data Rows

I'm working on a T-SQL issue where I needed to Transponse Rows into Columns and using UNPIVOT and PIVOT together per a post at Simple way to transpose columns and rows in Sql?

No problem. It does Exactly what I want with the row/column manipulation. However what I would REALLY like to do is to get the values used for the column headers to become yet another row in the results.

My abbreviated code is:

SELECT * 
FROM   (SELECT fiscalyear, 
              Sum(totalrecords)  AS TotalRecords 
        FROM   dbo.tbleirstatisticsoverviewsummary 
        WHERE  fiscalquarter = 'ALL' 
               AND branchcode = 'ALL' 
        GROUP  BY fiscalyear, 
                  fiscalquarter, 
                  branchcode) AS p 
       UNPIVOT (value 
               FOR colname IN ( totalrecords )) AS unpvt 
       PIVOT   (Max(value) For  FiscalYear IN ([2012],[2013],[ALL])) as  p  

What it renders is:
colname         2012 2013 ALL
TotalRecords 421   227   648

Where the first line is column headers.

Any thoughts on how I could get the column headers to be data rows?

Adding some sample Raw Data fiscalyear TotalRecords 2012 421 2013 227 ALL 648

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a few confusing things that you are doing.

First, typically you will unpivot multiple columns. Right now, you are are unpivoting one column and it seems like you are doing it just to rename the column?

Second, you are aggregating the data twice, the PIVOT should be able to handle the aggregation using SUM().

Third, it is not exactly clear on why you need the column headers as a row, what will you want the column headers to be called?

Based on your sample data you should be able to just apply the PIVOT function:

select 'TotalRecords' TotalRecords, 
  [2012],
  [2013],
  [All]
from tbleirstatisticsoverviewsummary
pivot
(
  sum(totalrecords)
  for FiscalYear IN ([2012],[2013],[ALL])
) p;

See SQL Fiddle with Demo. Then if you want a row with the columns headers, then you can use a UNION ALL:

select 'colname' col1, 
  2012 col2, 
  2013 col3, 
  'All' col4
union all
select 'TotalRecords' TotalRecords, 
  [2012],
  [2013],
  [All] = cast([all] as varchar(10))
from tbleirstatisticsoverviewsummary
pivot
(
  sum(totalrecords)
  for FiscalYear IN ([2012],[2013],[ALL])
) p;

See SQL Fiddle with Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...