I have a table that looks something like the following :
PropertyID Amount Type EndDate
--------------------------------------------
1
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
Try this:
SELECT
PropertyId,
SUM(Amount) as TOTAL_COSTS
FROM
MyTable
WHERE
EndDate IS NULL
GROUP BY
PropertyId
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
......
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 SUM
med, 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 GROUP
ing - for instance HAVING SUM(Amount) > 0