Search code examples
sqlt-sqlsumssrs-tablix

How to sort by Total Sum calculated field in a Tablix


I have a Report in Microsoft Visual Studio 2010 that has a tablix. I have a list of Customers Sales grouped by Month. I would like to add a grand total of all the Months for each customer. I would then like to sort by descending amount of the grand total. I have added the grand total, but I can't figure out how to sort on it. Any suggestions?

Here is the initial dataset query:

SELECT
Customer, CustomerName, FiscalMonthNum, FiscalYear, SalesDlr
FROM
CustomerSalesDollars
WHERE
FiscalYear IN ('2013')
ORDER BY
SalesDlr DESC

Solution

  • with CSD as (
        select Customer, CustomerName, FiscalMonthNum, FiscalYear, SalesDlr
        from CustomerSalesDollars
        WHERE FiscalYear in ('2013')
    ), YearlyTotals as (
        select FiscalYear, Customer, CustomerName, SUM(SalesDlr) as YearlyTotal
        from CSD
        group by FiscalYear, Customer, CustomerName
    )
    
    select * from YearlyTotals
    order by YearlyTotal desc
    

    If you still want all the monthly breakdowns:

    with CSD as (
        select Customer, CustomerName, FiscalMonthNum, FiscalYear, SalesDlr
        from CustomerSalesDollars
        WHERE FiscalYear in ('2013')
    ), YearlyTotals as (
        select FiscalYear, Customer, CustomerName, SUM(SalesDlr) as YearlyTotal
        from CSD
        group by FiscalYear, Customer, CustomerName
    )
    
    select CSD.*, YT.YearlyTotal from YearlyTotals YT
    join CSD on CSD.FiscalYear = YT.FiscalYear
    and CSD.Customer = YT.Customer
    and CSD.CustomerName = YT.CustomerName
    order by YearlyTotal desc, CSD.SalesDlr desc