我有一个带有cost_maintence列的表,它花费了整整一年(52)个星期的时间。我还有一个租房者表和一个renter_units表,其中有一个week_owned列,其中包含租房者租用的周号。我正在设法弄清楚如何计算每一个租房者的费用。我想出的方程式是:
每个人所欠的=(成本_maintence/52)**每个租客租用的周
有什么方法可以从查询中获得值吗?
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;
发布于 2013-10-24 19:03:25
下面是一个例子。内部查询将为您获取每个项目所欠的金额,而外部查询将得到每个人的欠款总额。
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演示试一试
示例模式:
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美元(滑板3周,每周1美元,喷火器2周,每周2美元)。
内部查询提供以下内容:
FNAME UNIT_NAME OWES
Chaz Skateboard 3
Chaz Flamethrower 4
以及外部:
FNAME TOTAL_DUE
Chaz 7
发布于 2013-10-24 18:56:59
SELECT t.renters_id, SUM(u.cost_maintence)/52
FROM unit u JOIN renters_unit t ON t.unit_id = u.id
GROUP BY t.renters_id
https://stackoverflow.com/questions/19574074
复制相似问题