我的表格结构如下:
units {id, owner_id}
contracts {id, rent, unit_id}
rents {paid, contract_id}
我需要的是两件事的总和:所有rents.paid
和contracts.rent
的总和。
我的查询是:
SELECT
Sum(Rent.paid) AS Rent__summed_rents
FROM
rents AS Rent
LEFT JOIN contracts
ON contracts.id = Rent.id
LEFT JOIN units
ON contracts.unit_id = units.id AND units.owner_id = 29
我尝试添加contracts.rent * Rent.paid AS Rent__summed_expected_rents
,但它没有用。
修改
每个contract
都有一列rent
,其中包含每个月预期的付款
每个rent
记录都有一列paid
,其中包含实际付款
查询应该获得所有付费记录并将它们相加(summed_rents),它还应该告诉我预期收入是多少(contracts.rent
* rents.paid)
*编辑#2 *
rents data:
id | paid | contract_id
1 | 200 | 6
1 | 300 | 6
1 | 500 | 4
1 | 200 | 4
contracts data:
id | rent | unit_id
6 | 500 | 22
4 | 600 | 22
units data:
id | owner_id
22 | 29
我的期望是:
总计租金= 1,200(所有已付款的总和)
预期租金= 2,200 =(500 * 2)+(600 * 2)(contract.rent的总和,每个rents
记录一个)
答案 0 :(得分:2)
以下是我构建查询的方法:
从拥有者的单位开始。很简单:
SELECT u.*
FROM units u
WHERE u.owner_id = 29
下一步,获取这些单位的合同:
SELECT c.*
, u.*
FROM units u
JOIN contracts c
ON c.unit_id = u.id
WHERE u.owner_id = 29
下一步,获得这些合同的租金
SELECT r.*
, c.*
, u.*
FROM units u
JOIN contracts c
ON c.unit_id = u.id
JOIN rents r
ON r.contract_id = c.id
WHERE u.owner_id = 29
- 通过合约ID汇总该结果的行(根据规范,我们需要按合约编号从租金计算,乘以合约租金金额)
SELECT SUM(r.paid) AS total_paid
, SUM(c.rent) AS total_rent
FROM units u
JOIN contracts c
ON c.unit_id = u.id
JOIN rents r
ON r.contract_id = c.id
WHERE u.owner_id = 29
GROUP BY c.id
- 通过将结果包装为内联视图并汇总total_paid和总租金来获得总计
SELECT SUM(t.total_paid) AS total_paid
, SUM(t.total_rent) AS total_rent
FROM (
SELECT SUM(r.paid) AS total_paid
, SUM(c.rent) AS total_rent
FROM units u
JOIN contracts c
ON c.unit_id = u.id
JOIN rents r
ON r.contract_id = c.id
WHERE u.owner_id = 29
GROUP BY c.id
) t
注意:计算给定合约的rents
中的行数似乎是获得租金乘数的奇怪方法。但如果这是规范,我们会确保我们的代码能够做到这一点。
我们只需要外部联接来产生“零”付费和“零”租金。如果我们向租户表引入LEFT JOIN,那么我们需要调整表达式以获得total_rent。我们想要使用类似的东西:
c.rent*COUNT(r.contract_id) AS total_rent
这样的事情:
SELECT IFNULL(SUM(t.total_paid),0) AS total_paid
, IFNULL(SUM(t.total_rent),0) AS total_rent
FROM (
SELECT SUM(r.paid) AS total_paid
, c.rent*COUNT(r.contract_id) AS total_rent
FROM units u
JOIN contracts c
ON c.unit_id = u.id
LEFT
JOIN rents r
ON r.contract_id = c.id
WHERE u.owner_id = 29
GROUP BY c.id
) t
答案 1 :(得分:1)
这很简单:
select sum(r.paid) as rent_paid,
sum(c.rent) as expected_rent
from rents r
join contracts c on (r.contract_id = c.id)
join units u on (c.unit_id = u.id)
where u.owner_id = 29;