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

I have a table that looks something like the following :

  PropertyID     Amount     Type       EndDate
 --------------------------------------------
   1              100       RENT        null              
   1              50        WATER       null         
   1              60        ELEC        null        
   1              10        OTHER       null      
   2              70        RENT        null
   2              10        WATER       null

There will be multiple items billed to a property, also billed multiple times. For example RENT could be billed to property #1 12 times (over a year), however the only ones I'm interested for are those with ENDDATE of null (in otherwords, current)

I would like to achieve :

    PropertyId       Amount
  --------------------------       
      1                220
      2                80

I have tried to do something like this :

SELECT
   propertyId,
   SUM() as TOTAL_COSTS
FROM
   MyTable

However, in the SUM would I be forced to have multiple selects bringing back the current amount for each type of charge? I could see this becoming messy and I'm hoping for a much simpler solution

Any ideas?

This question is related to sql sql-server tsql aggregate

The answer is


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

......


Try this:

SELECT
   PropertyId,
   SUM(Amount) as TOTAL_COSTS
FROM
   MyTable
WHERE
   EndDate IS NULL
GROUP BY
   PropertyId

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


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

sounds like you want something like:

select PropertyID, SUM(Amount)
from MyTable
Where EndDate is null
Group by PropertyID

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

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to tsql

Passing multiple values for same variable in stored procedure Count the Number of Tables in a SQL Server Database Change Date Format(DD/MM/YYYY) in SQL SELECT Statement Stored procedure with default parameters Format number as percent in MS SQL Server EXEC sp_executesql with multiple parameters SQL Server after update trigger How to compare datetime with only date in SQL Server Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot Printing integer variable and string on same line in SQL

Examples related to aggregate

Pandas group-by and sum SELECT list is not in GROUP BY clause and contains nonaggregated column Aggregate multiple columns at once Pandas sum by groupby, but exclude certain columns Extract the maximum value within each group in a dataframe How to group dataframe rows into list in pandas groupby Mean per group in a data.frame Summarizing multiple columns with dplyr? data.frame Group By column Compute mean and standard deviation by group for multiple variables in a data.frame