无法在子查询上执行聚合函数

时间:2009-12-22 14:50:40

标签: tsql subquery aggregate

有人可以帮我解决这个问题吗?

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

我遇到了第二笔钱的问题,它不会让我这样做。显然,SUM不会对子查询起作用,但是我需要计算预期的租金(如果有租户分配给RentalUnit的id,则为MonthlyRent,其中0不是)。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:6)

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

这是一个要检查的测试脚本:

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

答案 1 :(得分:0)

对于某些特定的出租单位(COUNT(t.ID) * ru.MonthlyRent),unitMonthlyRent的总和乘以租户数的含义是什么?

是否所有你想要做的就是看到所有的非潜在租金与预期租金之间的差异(仅来自有效单位)?如果是这样,那么试试这个

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