任何人都可以帮我构建一个oracle查询,以获得低于预期的结果 我有2个表,命名为 detention_charge_slot 和 detention_invoice 示例如下
create table detention_charge_slot
(slot_no number(5),
from_days number(10),
to_days number(10),
charge_amount number(10,2));
insert into detention_charge_slot
values (1,1,4,0);
insert into detention_charge_slot
values (2,5,9,10);
insert into detention_charge_slot
values (3,10,14,20);
insert into detention_charge_slot
values (4,15,999,25);
create table detention_invoice
(invoice_no number(10),
invoice_dt date,
delivery_dt date);
insert into detention_invoice
values(1,'10-JAN-2015','25-JAN-2015');
现在我想为invoice_no = 1写一个查询,它会给我以下结果
Start_date | End_date | Days| Charge_Amount
10-JAN-2015 13-JAN-2015 4 0
14-JAN-2015 18-JAN-2015 5 10
19-JAN-2015 23-JAN-2015 5 20
24-JAN-2015 25-JAN-2015 2 25
答案 0 :(得分:0)
SQL查询中的谓词可以基于表达式,例如:
SELECT Charge
FROM date_range_charge
WHERE From_days <= (TO_DATE(:param2,'DD-MON-YYYY')
- TO_DATE(:param1,'DD-MON-YYYY') + 1)
AND To_days >= (TO_DATE(:param2,'DD-MON-YYYY')
- TO_DATE(:param1,'DD-MON-YYYY') + 1);
答案 1 :(得分:0)
select invoice_dt + from_days - 1 start_date,
invoice_dt + to_days -1 end_date,
to_days-from_days + 1 days, charge_amount
from detention_charge_slot dcs
join detention_invoice di on (di.invoice_no = 1)
order by slot_no
result:
START_DATE END_DATE DAYS CHARGE_AMOUNT
2015-01-10 2015-01-13 4 0,00
2015-01-14 2015-01-18 5 10,00
2015-01-19 2015-01-23 5 20,00
2015-01-24 2017-10-04 985 25,00
最后一行是不同的,因为你在detention_charge_slot.to_days
中放了999。如果你想要2那么修改查询就像这里:
select invoice_dt + from_days - 1 start_date,
least(invoice_dt + to_days - 1, delivery_dt) end_date,
least(invoice_dt + to_days - 1, delivery_dt) - (invoice_dt + from_days - 2) days,
charge_amount
from detention_charge_slot dcs
join detention_invoice di on (di.invoice_no = 1)
order by slot_no
result:
START_DATE END_DATE DAYS CHARGE_AMOUNT
2015-01-10 2015-01-13 4 0,00
2015-01-14 2015-01-18 5 10,00
2015-01-19 2015-01-23 5 20,00
2015-01-24 2015-01-25 2 25,00