我有如下表格:
create table company
(
id int(10) unsigned not null auto_increment,
name varchar(50) not null,
primary key (id)
);
create table invoice
(
id int(10) unsigned not null auto_increment,
company_id int(10) unsigned not null,
invoice_number varchar(50) not null,
paid_date datetime not null,
paid_amount decimal(10, 2) not null,
primary key (id),
foreign key (company_id) references company(id)
);
create table company_rate
(
id int(10) unsigned not null auto_increment,
company_id int(10) unsigned not null,
rate decimal(10, 2) not null,
effective_date datetime not null,
primary key (id),
foreign key (company_id) references company(id)
);
公司表包含公司的名称。发票表包含发票编号、公司收到付款的日期和金额。公司费率表保存费率和费率生效的开始日期。例如,
company_id rate effective_date
-------------------------------------
1 100 0000-00-00
1 350 2013-07-01
1 450 2013-07-20
1 500 2014-01-01
如果当前日期是 07-03,那么汇率是 350,如果日期是 09-21,汇率是 450,依此类推。
我正在尝试根据这些表创建两个函数。
一种是通过选择公司来创建发票,并使用 html 表单或其他方式根据生效日期显示当前费率。
另一种是创建这样的列表:
company_name invoice_number rate paid_amount paid_date
-------------------------------------------------------------------
Apple 12345 300 300 2013-01-14
Apple 12346 500 400 2013-05-12
Intel 44441 1200 1350 2013-06-01
它打印发票信息,费率由paid_date 确定。
这是试过的:
SELECT c.name as company_name, i.invoice_number, r.rate, i.paid_amount, i.paid_date
FROM invoice as i
LEFT JOIN company as c on c.id = i.company_id
LEFT JOIN (
SELECT company_id, rate, effective_date
FROM company_rate
WHERE effective_date IN (
SELECT MAX(effective_date)
FROM company_rate
GROUP BY company_id
)) AS r ON r.company_id = c.id
AND r.effective_date <= i.paid_date
我怎样才能做到这一点?