我有一个包含 cost_maintence 列的表,其中包含全年(52)周的成本。我还有一个租户表和一个renter_units 表,其中有一个week_owned 列,其中包含租户租用的周数。我想弄清楚如何计算每个租户的费用。我想出的等式是:
what each person owes = (cost_maintence/52) * #weeks each renter rented
有什么方法可以从查询中获取值吗?
create table renters(
id,
lname,
fname,
phone_num);
create table unit(
id,
unit_name,
unit_num,
cost_maintence);
create table renters_unit(
renters_id,
unit_id,
week_owned);
这是我提出的查询,但我无法测试它
select r.lname, r.fname, count(ru.week_owned),
sum(u.cost_maintence/52*count(ru.week_owned))
from renters r, renters_units ru, units u
where r.id = ru.renter_id
and ru.unit_id = u.id
and u.unit_name =unitname
and u.unit_num = unitnum
group by lname
order by lname,fname asc;
最佳答案
这是一个例子。内部查询将获取每件商品的欠款金额,外部查询将其相加得出每人的欠款总额。
SELECT fname, SUM(owes) AS total_due
FROM (
SELECT r.fname,
r.id,
u.unit_name,
u.cost_maintence/52*COUNT(ru.week_owned) AS owes
FROM renters AS r
INNER JOIN renters_unit AS ru ON r.id = ru.renters_id
INNER JOIN unit AS u ON u.id = ru.unit_id
GROUP BY r.id, u.id
) AS t
GROUP BY id
尝试一下 SQLFiddle demo
示例架构:
create table renters(
id int,
lname varchar(20),
fname varchar(20),
phone_num varchar(20));
create table unit(
id int,
unit_name varchar(30),
unit_num int,
cost_maintence int);
create table renters_unit(
renters_id int,
unit_id int,
week_owned int);
INSERT INTO renters VALUES (1, 'Peterson', 'Chaz', '8675309');
INSERT INTO unit VALUES (1, 'Skateboard', 1337, 52);
INSERT INTO unit VALUES (2, 'Flamethrower', 5432, 104);
INSERT INTO renters_unit VALUES (1, 1, 1);
INSERT INTO renters_unit VALUES (1, 1, 2);
INSERT INTO renters_unit VALUES (1, 1, 4);
INSERT INTO renters_unit VALUES (1, 2, 4);
INSERT INTO renters_unit VALUES (1, 2, 5);
由此,我们可以看出 Chaz 今年应欠 7 美元(以每周 1 美元的价格购买滑板 3 周,以每周 2 美元的价格购买火焰喷射器 2 周)。
内部查询给出以下内容:
FNAME UNIT_NAME OWES
Chaz Skateboard 3
Chaz Flamethrower 4
外部:
FNAME TOTAL_DUE
Chaz 7
关于mysql - SQL 中的方程 (MySQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19574074/