我有一个类似这样的表数据结构:
楼主表
Id Name Email
```````````````````````
1 J Johnson ...
2 R Kelly ...
属性表
Id Address Rent LandlordId
```````````````````````````````````
1 .... 400 1
2 .... 600 1
3 .... 750 2
保养表
Id Details Cost MaintenanceDate PropertyId
`````````````````````````````````````````````````````
1 .... 25 20/12/2012 1
2 .... 120 22/12/2012 2
3 .... 35 24/12/2012 3
从本质上讲,房东有多个属性(property)。每个月,我需要为房东开具发票,其中包括他的所有属性(property),以及对其属性(property)进行的所有维护。要计算我需要付给房东多少钱,我需要将他所有特性的租金相加,然后减去他当月所有维护费用的总和。
因此,应付给房东 L 的金额 = Sum(L 的特性租金)- Sum(L 在本月所有特性的维护费用)
我正在使用 telerik 报告,我认为我可以通过一些巧妙的分组来实现它,但那是在浪费我的时间,所以我现在将尝试使用 SQL 和子报告来实现它。
我正在尝试的 SQL 查询是这样的:
SELECT l.Name, p.[Address], p.Rent, c.Details, c.Cost,
(select Rent From Property where Id = p.Id) -
(select SUM(cost) from CarriedOutJobs where PropertyId = p.Id)
as PayableToLandlord
FROM Landlord l JOIN PROPERTY p ON p.LandlordId = l.Id
LEFT OUTER JOIN Maintenance c ON c.PropertyId = p.Id
ORDER BY l.Fullname
这似乎不能正常工作,因为它会产生多个字段
因为我要把报告分解成子报告,我想我会先得到房东的详细信息,但即使在这种情况下我仍然需要计算应付给房东的金额。所以我将查询重写为:
SELECT distinct l.Name,
(SELECT SUM(Rent) FROM PROPERTY WHERE LandlordId = l.Id) -
(SELECT COALESCE(SUM(cost), 0)
FROM CarriedOutJobs WHERE PropertyId = p.Id) AS PayableToLandlord
FROM Landlord l
JOIN PROPERTY p ON p.LandlordId = l.Id
ORDER BY l.Fullname
我认为这行得通,但即使我使用了 distinct,这似乎会产生一个具有不同 PayableToLandlord
金额的重复行,我似乎无法弄清楚原因。
有没有一种方法可以在一次查询中选择所有房东、他们的属性(property)以及应付给他们的金额?
为了简单起见,我在这里删除了 date where 子句。
谢谢。
最佳答案
我建议保持简单并使用子查询,因为这些很容易弄清楚发生了什么。希望您可以在报告中或作为额外的返回列进行减法等。 您应该将任何日期参数作为变量传递给子查询(可能)。
SELECT Landlord.Id as LandlordId, Landlord.Name,
ISNULL(TotalRent,0) AS TotalRent,
ISNULL(TotalCost,0) AS TotalCost
FROM Landlord
LEFT JOIN
(SELECT SUM(Rent) as TotalRent, LandLordId
FROM Property
GROUP BY LandLordId) Rents
ON Landlord.Id = Rents.LandlordId
LEFT JOIN
(SELECT LandLordId,SUM(Cost) AS TotalCost
FROM Property
INNER JOIN Maintenance
ON Property.Id = Maintenance.PropertyId
GROUP BY LandLordId
) MaintenanceCosts
ON Landlord.Id = MaintenanceCosts.LandlordId
ORDER BY Landlord.Name
刚注意到你还写了:
Is there a way to select all landlords, their properties, and the amount payable to them in one query, please?
您可以进一步加入属性列表,但您最终会在每一行上重复求和。只要您不尝试在报告包中对其进行 SUM,就可以了。
如果您确实需要特性的详细信息,那么我的建议是提取每个特性的租金和成本,然后在报告包中计算总和/净值。
关于sql - 复杂的 sql 查询 - 在一个查询中选择所有房东的属性并减去成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14023942/