0

我有一个带有 cost_maintence 列的表,该列的成本为整年(52)周。我还有一个租户表和一个renter_units 表,其中有一个 week_owned 列,其中包含租户租用的周数。我试图弄清楚如何计算每个租户的成本。我想出的等式是:

每个人的欠款 = (cost_maintence/52) * #weeks 每个租户租用的

有什么办法可以从查询中获取值?

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;
4

2 回答 2

1

这是一个例子。内部查询将为您提供每件物品的欠款,外部查询将其相加以找到每人的欠款总额。

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-24T19:03:25.120 回答
0
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
于 2013-10-24T18:56:59.333 回答