Pivot table returns multiple rows with NULL, results should be grouped on one row

前端 未结 1 778
时光取名叫无心
时光取名叫无心 2021-02-05 11:53

I have the table below which I am looking to pivot so that the descriptions in column 1 become column headers in the new pivot.

 Nominal Group  | GrpID | Descri         


        
1条回答
  •  误落风尘
    2021-02-05 12:20

    Any columns that are available are passed to the PIVOT function, so all apart from the column aggregated, and the column pivoted are implicitly grouped by, so since GrpID and Description are present, and not included it is grouped by, therefore you get one row per combination of these. You need to limit the columns passed to the pivot function by using a subquery:

    SELECT  pvt.CustomerID,
            pvt.Sales,
            pvt.[Cost of Sales],
            pvt.[Labour Costs],
            pvt.[Overheads]
    FROM    (   SELECT  CustomerID, nominalgroupname, Value
                FROM    trialbalancegrouping
            ) AS t
            PIVOT
            (   SUM(Value)
                FOR nominalgroupname IN 
                    (   [Sales],[Cost of Sales],
                        [Labour Costs],[Overheads]
                    )
            ) AS pvt;
    

    0 讨论(0)
提交回复
热议问题