Replace NULL in a ROLLUP

Antonio José Esis Ochoa 6 Reputation points
2022-05-28T15:05:25.803+00:00

Hello, I would like to replace the NULL in the final row when using the ROLLUP, for any other word like 'Total'.

SELECT
SalesOrderID,
SUM(UnitPrice*OrderQty) AS Total
FROM
Sales.SalesOrderDetail
GROUP BY
SalesOrderID WITH ROLLUP

Developer technologies Transact-SQL
{count} vote

2 answers

Sort by: Most helpful
  1. Tom Cooper 8,481 Reputation points
    2022-05-28T15:17:26.337+00:00

    Since SalesOrderID is an integer and the word 'Total' is a varchar value, you must convert the SalesOrderID to varchar and then use ISNULL, for example

    SELECT
    IsNull(Cast(SalesOrderID As varchar(11)), 'Total'),
    SUM(UnitPrice*OrderQty) AS Total
    FROM
    Sales.SalesOrderDetail
    GROUP BY
    SalesOrderID WITH ROLLUP
    

    Tom

    2 people found this answer helpful.

  2. Bert Zhou-msft 3,436 Reputation points
    2022-05-30T01:51:12.883+00:00

    Hi,@Antonio José Esis Ochoa

    Welcome to Microsoft T-SQL Q&A Forum!

    Try this:

    SELECT  
    case when  SalesOrderID is null then 'Total'   
            else CAST(SalesOrderID as varchar(10))   
            end SalesOrderID,  
    SUM(UnitPrice*OrderQty) AS Total  
    FROM  
    Sales.SalesOrderDetail  
    GROUP BY SalesOrderID with ROLLUP;  
    

    Best regards,
    Bert Zhou


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.