简体   繁体   English

使用SQL PIVOT从列到行…SQL Server 2008 R2

[英]Columns to Rows using SQL PIVOT… SQL Server 2008 R2

I have to transpose all the Rows from a table to columns in SQL Server 2008 R2... I have used Pivot to transpose multiple rows of one column into one row with multiple columns. 我必须将所有从表中的行转置为SQL Server 2008 R2中的列...我已使用Pivot将一列的多行转置为具有多列的一行。 I am not sure how I can use pivot in this scenario... 我不确定在这种情况下如何使用数据透视...

I would like to pivot the table based on the "EXPENSE" column 我想根据“ EXPENSE”列来透视表

SQL Fiddle SQL小提琴

The desired output is 所需的输出是

在此处输入图片说明

Meanwhile I will try to explore the related posts suggested.... 同时,我将尝试探索建议的相关职位。

Thank you so much for the suggestions... 非常感谢您的建议...

Based on your desired results it looks like you need to do an unpivot transform followed by a pivot, like this: 根据所需的结果,看起来您需要先进行无轴转换,然后再进行轴转换,如下所示:

select 
    YEAR, 
    [Bps on Assets],[Setup Fee],[Account Min],[BAA Fees],[RedTail Fees (CRM)],
    [RedTail Fees (Per User)],[External IT],[External IT Setup] 
from (
    select Expense, value, year 
    from SM_TechBundleExpnsRates
    unpivot (
       value FOR year IN ([Year1], [Year2], [Year3], [Year4], [Year5]) 
    ) up 
) a
pivot (
    sum(value) for expense in 
          (
           [Bps on Assets],[Setup Fee],[Account Min],
           [BAA Fees],[RedTail Fees (CRM)],
           [RedTail Fees (Per User)],[External IT],[External IT Setup]
          )
) p

Sample SQL Fiddle 示例SQL提琴

Note that this isn't dynamic in any way, but rather uses hard coded column values for the years and expenses. 请注意,这绝不是动态的,而是使用硬编码的列值来表示年数和费用。 It's possible to generate the code in a dynamic fashion - if you want to know how there are plenty of good answers showing how to do dynamic pivot with SQL Server. 可以以动态方式生成代码-如果您想知道如何有很多好的答案来说明如何使用SQL Server进行动态数据透视。

Edit: did the dynamic version for fun, it might not be perfect but it should work: 编辑:做了动态版本的乐趣,它可能不是完美的,但它应该工作:

DECLARE @sql AS NVARCHAR(MAX)
DECLARE @year_cols AS NVARCHAR(MAX)
DECLARE @expe_cols AS NVARCHAR(MAX)

SELECT @expe_cols= ISNULL(@expe_cols + ',','') + QUOTENAME(Expense)
FROM (SELECT DISTINCT Expense FROM SM_TechBundleExpnsRates) AS Expenses

SELECT @year_cols= ISNULL(@year_cols + ',','') + QUOTENAME(year) 
FROM (
    SELECT c.name AS year 
    FROM sys.tables t JOIN sys.columns c ON t.object_id = c.object_id 
    WHERE t.name = 'SM_TechBundleExpnsRates' AND c.name LIKE '%Year%'
) AS Years


SET @sql = N'
SELECT 
    Year, ' + @expe_cols + '    
FROM (
    SELECT Expense, Value, Year 
    FROM SM_TechBundleExpnsRates
    UNPIVOT ( Value FOR Year IN (' + @year_cols + ') ) AS up
) a PIVOT ( SUM(Value) FOR Expense IN (' + @expe_cols + ') ) p'

EXEC sp_executesql @sql

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM