sql中的pivot - 从数据透视表列生成总计列

时间:2011-10-27 13:29:01

标签: sql-server-2005

以下查询工作正常,我根据需要获得数据透视表。美元数量在1月至12月期间显示正常。现在,我如何添加一个总列,从1月到12月可以给我一行?由于这些月份列是使用pivot创建的,因此我不确定如何为所有月份添加值并在新列中显示。能否请你帮忙?如果您需要更多关于我正在寻找的内容,请告诉我。

提前致谢!

CREATE TABLE #t
    (
        Region varchar(50),
        Area varchar(255),
        Market varchar(255),
        MediaType varchar(50),
        Campaign varchar(255),
        Description varchar(255),
        TotalCost money,
        MonthDesc nvarchar(50),
        [Year] int,
        MonthNumber int
    )
    DECLARE @List VARCHAR(8000), @SQL VARCHAR(8000)
    SET @List = ''
    SET @SQL = ''

    INSERT INTO #t
    SELECT 
        r.RegionName,
        d.DistrictName,
        dm.DMAName,
        mt.MediaTypeDesc,
        pn.PlanName,
        pd.VendorPreference,
        SUM(pd.DropAmount) AS TotalCost,
        DATENAME(MONTH, pd.StartDate),
        p.[Year],
        DATEPART(MONTH, pd.StartDate)
    FROM PlanDetails pd
    INNER JOIN Plans p ON p.PlanId = pd.PlanId
    INNER JOIN PlanNames pn ON pn.PlanNameId = p.PlanNameId
    INNER JOIN DMA_Plans dp ON p.PlanId = dp.PlanId
    INNER JOIN DMA dm ON dm.DMAId = dp.DMAId
    INNER JOIN Centers c ON c.DMAId = dm.DMAId
    INNER JOIN Districts d ON d.DistrictId = c.DistrictId
    INNER JOIN Regions r ON r.RegionId = d.RegionId
    INNER JOIN MediaTypes mt ON mt.MediaTypeId = pd.MediaTypeId
    WHERE   c.OrganizationId = 2
    AND     p.[Year] = @Year
    AND     pd.StartDate IS NOT NULL
    AND     p.Active = 1
    AND     c.DMAId IS NOT NULL
    AND     pd.MediaTypeId IS NOT NULL
    GROUP BY    r.RegionName,
                d.DistrictName,
                dm.DMAName,
                mt.MediaTypeDesc,
                pn.PlanName,
                pd.VendorPreference,
                pd.StartDate,
                p.[Year]

    DECLARE @TblY TABLE(ODate nvarchar(50), oYear int, oMonthOrder int)
    INSERT @TblY 
    SELECT  DISTINCT MonthDesc, [Year], MonthNumber FROM [#t] ORDER BY MonthNumber

    SELECT @List = ISNULL(@List,'') + CASE WHEN ISNULL(@List,'') = '' THEN '[' + ODate + ']' ELSE ',[' + ODate + ']' end
    FROM @TblY
    ORDER BY oMonthOrder

    SET @SQL = 'Select Region, Area, Market, MediaType, Campaign, Description, ' + @List + char(13) 
    SET @SQL = @SQL + 'From (Select Region, Area, Market, MediaType, Campaign, Description, MonthDesc, TotalCost ' + char(13) 
    SET @SQL = @SQL + 'FROM #t F) P ' + char(13) 
    SET @SQL = @SQL + 'Pivot (SUM(TotalCost) For MonthDesc In ('  + @List + ')) as Pvt' + char(13) 


    PRINT @SQL
    EXEC (@SQL)

    DROP TABLE #t

1 个答案:

答案 0 :(得分:1)

使用分组集或CUBE

分组集基本上是一个多个group by语句。 将此与将枢轴视为子选择相结合,您可以通过快速简便的方法在同一结果集中实现聚合总计

有关groping集的更多信息 http://msdn.microsoft.com/en-us/library/bb522495.aspx http://blogs.msdn.com/b/sreekarm/archive/2008/12/28/grouping-sets-in-sql-server-2008.aspx