使用Pivot转置SQL表结果

时间:2016-12-09 16:22:57

标签: sql pivot transpose

我正在尝试将我的表中的列结果转换为行结果。以下是生成表结果的查询:

 CREATE TABLE Zone 
        ([Zone] varchar(9), [CompanyID] int, [SubCount] int);

    CREATE TABLE Company
         ([UniqueIdentifier]int, [Name] varchar(50));

    --Adding Values into the table

    INSERT INTO Company 
        ([UniqueIdentifier], [Name])
    VALUES
        ( 1, 'CompanyA'),
        ( 2, 'CompanyB'),
        ( 3, 'CompanyC'),
        ( 4, 'CompanyD'),
        ( 5, 'CompanyE');

    --Adding Values to the table

    INSERT INTO Zone
        ([Zone], [CompanyID], [SubCount])
    VALUES
        ( 'Zone1', 1, 100),
        ( 'Zone2', 1, 200),
        ( 'Zone3', 2, 1250),
        ( 'Zone4', 3, 1440),
        ( 'Zone5', 4, 1445),
        ( 'Zone6', 4, 3250),
        ( 'Zone7', 5, 4440);

    --Getting TOTALS

    SELECT
    CASE WHEN GROUPING(dbo.Company.Name)=1 THEN 'Grand Total' else  dbo.Company.Name end as Company,
    SUM(dbo.Zone.SubCount) as Subs 

    FROM dbo.Company INNER JOIN dbo.Zone ON dbo.Company.UniqueIdentifier = dbo.Zone.CompanyID 

    WHERE (dbo.Zone.SubCount IS NOT NULL) AND (dbo.Zone.SubCount > 0)

    Group by ROLLUP(dbo.Company.Name)

    ORDER BY Subs DESC;

这是“查询”的结果:

    Company     | Subs
------------------------
1   Grand Total | 12125
2   CompanyD    | 4695
3   CompanyE    | 4440
4   CompanyC    | 1440
5   CompanyB    | 1250
6   CompanyA    | 300

渴望得到的结果:

 Company |CompanyA|CompanyB|CompanyC|CompanyE|CompanyD|Grand Total  
---------------------------------------------------------------------
 Subs    |  300   |  1250  |  1440  |  4440  |  4695  |   12125

任何帮助都非常受欢迎!

1 个答案:

答案 0 :(得分:1)

您需要做的就是使用pivot函数将这些行转换为列

errorcode 1
upload error source file:///storage/emulated/0/DCIM/Camera/IMG_20161209_120808.jpg
upload error target https://my.url.com