SQL Server : SUM() of multiple rows including where clauses

后端 未结 6 1601
死守一世寂寞
死守一世寂寞 2020-11-30 02:19

I have a table that looks something like the following :

  PropertyID     Amount     Type       EndDate
 --------------------------------------------
   1           


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 03:07

    Use a common table expression to add grand total row, top 100 is required for order by to work.

    With Detail as 
    (
        SELECT  top 100 propertyId, SUM(Amount) as TOTAL_COSTS
        FROM MyTable
        WHERE EndDate IS NULL
        GROUP BY propertyId
        ORDER BY TOTAL_COSTS desc
    )
    
    Select * from Detail
    Union all
    Select ' Total ', sum(TOTAL_COSTS) from Detail
    

提交回复
热议问题