Unable to perform aggregate function in subquery

Can someone help me with this request?

SELECT p.OwnerName, SUM(ru.MonthlyRent) AS PotentinalRent,  SUM(
    (SELECT COUNT(t.ID) * ru.MonthlyRent FROM tblTenant t 
      WHERE t.UnitID = ru.ID)
    ) AS ExpectedRent
 FROM tblRentalUnit ru
LEFT JOIN tblProperty p ON p.ID = ru.PropertyID
GROUP BY p.OwnerName

I have problems with the second amount, this will not allow me to do this. Obviously, SUM will not work on subqueries, but I need to calculate the expected rent (MonthlyRent, if there is a tenant assigned with RentalUnit identifier, 0 of them are not). How can I do this job?

+5
source share
2 answers
SELECT  p.OwnerName, SUM(ru.MonthlyRent) AS PotentialRent, SUM(cnt) AS ExpectedRent
FROM    tblRentalUnit ru
LEFT JOIN
        tblProperty p
ON      p.ID = ru.PropertyID
OUTER APPLY
        (
        SELECT  COUNT(t.id) * ru.MonthlyRent AS cnt
        FROM    tblTenant t
        WHERE   t.UnitID = ru.ID
        ) td
GROUP BY p.OwnerName

Here's a test script to verify:

WITH    tblRentalUnit AS
        (
        SELECT  1 AS id, 100 AS MonthlyRent, 1 AS PropertyID
        UNION ALL
        SELECT  2 AS id, 300 AS MonthlyRent, 2 AS PropertyID
        ),
        tblProperty AS
        (
        SELECT  1 AS id, 'Owner 1' AS OwnerName
        UNION ALL
        SELECT  2 AS id, 'Owner 2' AS OwnerName
        ),
        tblTenant AS
        (
        SELECT  1 AS id, 1 AS UnitID
        UNION ALL
        SELECT  2 AS id, 1 AS UnitID
        )
SELECT  p.OwnerName, SUM(ru.MonthlyRent) AS PotentialRent, SUM(cnt) AS ExpectedRent
FROM    tblRentalUnit ru
LEFT JOIN
        tblProperty p
ON      p.ID = ru.PropertyID
OUTER APPLY
        (
        SELECT  COUNT(t.id) * ru.MonthlyRent AS cnt
        FROM    tblTenant t
        WHERE   t.UnitID = ru.ID
        ) td
GROUP BY p.OwnerName
+6
source

What is the meaning of the unit sum of MonthlyRent times the number of tenants for some partial rental unit ( COUNT(t.ID) * ru.MonthlyRent)?

, , , - ( )? ,

Select p.OwnerName, 
   Sum(r.MonthlyRent) AS PotentinalRent,  
   Sum(Case t.Id When Null Then 0 
         Else r.MonthlyRent End) ExpectedRent
From tblRentalUnit r
    Left Join tblTenant t 
      On t.UnitID = r.ID
    left Join tblProperty p
       On p.ID = r.PropertyID)
Group By p.OwnerName
0

All Articles