简体   繁体   中英

Adding a total row in SQL Server 2005?

I have a script that creates a report however I require a total row at the bottom.

In SQL Server 2008 I think I would use roll up but I cannot work out how to do this in SQL Server 2005.

USE FEN
    GO
    SELECT 
        PMC.Store_ID,
        PMC.Name,
        SUM (PMC.[Net Sales] / 1000) AS 'Daily Sales',
        SUM  (PMCLY.[Net Sale LY] / 1000) AS 'Daily Sales LY',
        CAST(100.0*(PMC.[Net Sales] - PMCLY.[Net Sale LY]) / PMCLY.[Net Sale LY] AS Decimal (10,2)) AS 'VAR % Vs LY',
        SUM (PMCW.[Net Sales Week] / 1000) AS 'Daily Sales Week',
        SUM (PMCLYW.[Net Sale Week LY] /1000) AS 'Daily Sales Week LY',
        CAST(100.0*(PMCW.[Net Sales Week] - PMCLYW.[Net Sale Week LY]) / PMCLYW.[Net Sale Week LY] AS Decimal (10,2)) AS 'VAR % Vs LY'

    FROM PMC_DailySalesReport AS pmc
        JOIN PMC_DailySalesReportLY as pmcly on pmcly.Store_ID = pmc.Store_ID
        JOIN PMC_DailySalesReportWeek as PMCW on pmcw.Store_ID = pmc.Store_ID
        JOIN PMC_DailySalesReportLYWeek AS PMCLYW on PMCLYW.Store_ID = PMC.Store_ID
    GROUP BY 
        PMC.Store_ID,
        PMC.Name, 
        PMC.[Net Sales],
        PMCLY.[Net Sale LY],
        PMCLYW.[Net Sale Week LY],
        PMCW.[Net Sales Week]

    go

The aim is to add total to bottom of the table for all the columns about from StoreID and Store Name

Any ideas?

I would expect you can add a UNION ALL which selects a row containing the aggregates without any of the grouping, which should give you a figure for all the rows:

 -- your query above, and then:
UNION ALL
SELECT 
    'All' As Store_ID,
    'All' As Name,
    SUM (PMC.[Net Sales] / 1000) AS 'Daily Sales',
    SUM  (PMCLY.[Net Sale LY] / 1000) AS 'Daily Sales LY',
    CAST(100.0*(PMC.[Net Sales] - PMCLY.[Net Sale LY]) / PMCLY.[Net Sale LY] AS Decimal (10,2)) AS 'VAR % Vs LY',
    SUM (PMCW.[Net Sales Week] / 1000) AS 'Daily Sales Week',
    SUM (PMCLYW.[Net Sale Week LY] /1000) AS 'Daily Sales Week LY',
    CAST(100.0*(PMCW.[Net Sales Week] - PMCLYW.[Net Sale Week LY]) / PMCLYW.[Net Sale Week LY] AS Decimal (10,2)) AS 'VAR % Vs LY'
FROM PMC_DailySalesReport AS pmc
    JOIN PMC_DailySalesReportLY as pmcly on pmcly.Store_ID = pmc.Store_ID
    JOIN PMC_DailySalesReportWeek as PMCW on pmcw.Store_ID = pmc.Store_ID
    JOIN PMC_DailySalesReportLYWeek AS PMCLYW on PMCLYW.Store_ID = PMC.Store_ID

It may not be quite as simple as that, given that in the main query you've got some extra group by fields which don't actually appear directly in the select, but that's the general idea. Without seeing the schema, sample data and expected output, it's hard to be more precise (because it's impossible to test the query).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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