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

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

I have a table that looks something like the following :

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


        
相关标签:
6条回答
  • 2020-11-30 02:55

    you mean getiing sum(Amount of all types) for each property where EndDate is null:

    SELECT propertyId, SUM(Amount) as TOTAL_COSTS
      FROM MyTable
     WHERE EndDate IS NULL
    GROUP BY propertyId
    
    0 讨论(0)
  • 2020-11-30 03:01

    sounds like you want something like:

    select PropertyID, SUM(Amount)
    from MyTable
    Where EndDate is null
    Group by PropertyID
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-30 03:14

    Try this:

    SELECT
       PropertyId,
       SUM(Amount) as TOTAL_COSTS
    FROM
       MyTable
    WHERE
       EndDate IS NULL
    GROUP BY
       PropertyId
    
    0 讨论(0)
  • 2020-11-30 03:15

    This will bring back totals per property and type

    SELECT  PropertyID,
            TYPE,
            SUM(Amount)
    FROM    yourTable
    GROUP BY    PropertyID,
                TYPE
    

    This will bring back only active values

    SELECT  PropertyID,
            TYPE,
            SUM(Amount)
    FROM    yourTable
    WHERE   EndDate IS NULL
    GROUP BY    PropertyID,
                TYPE
    

    and this will bring back totals for properties

    SELECT  PropertyID,
            SUM(Amount)
    FROM    yourTable
    WHERE   EndDate IS NULL
    GROUP BY    PropertyID
    

    ......

    0 讨论(0)
  • 2020-11-30 03:17

    The WHERE clause is always conceptually applied (the execution plan can do what it wants, obviously) prior to the GROUP BY. It must come before the GROUP BY in the query, and acts as a filter before things are SUMmed, which is how most of the answers here work.

    You should also be aware of the optional HAVING clause which must come after the GROUP BY. This can be used to filter on the resulting properties of groups after GROUPing - for instance HAVING SUM(Amount) > 0

    0 讨论(0)
提交回复
热议问题