我有两张桌子:
我想找到与发票记录相关联的成本记录,以创建保证金报告。
例如,从发票表中订购1004,我想从该文件中获取日期和时间,并根据该日期和时间(等于或小于)查找成本。
订单1004具有171543的04/15时间,其将链接日期04/15和时间171523的成本表记录。
有关我希望如何查看输出的详细信息,请参见下图。
提前致谢
发票档案
Order1 Item1 Sales1 Date1 Time1
1001 | A1001 | 10.00 |04/15 |151025
1002 | A1001 | 12.00 |04/15 |151112
1003 | A1001 | 11.00 |04/15 |171235
1004 | A1001 | 14.00 |04/15 |171543
1005 | A1001 | 13.50 |04/15 |171855
费用文件
Item2 Cost2 Date2 Time2
A1001 | 3.50 |04/14 |171255
A1001 | 4.20 |04/15 |151233
A1001 | 2.50 |04/15 |171523
A1001 | 4.00 |04/15 |171623
输出布局 - 保证金报告
Order |Item |Sales |Cost |Margin
1001 |A1001 |10.00 |3.50 | 6.50
1002 |A1001 |12.00 |3.50 | 8.50
1003 |A1001 |11.00 |2.50 | 8.50
1004 |A1001 |14.00 |2.50 | 11.50
1005 |A1001 |13.50 |4.00 | 9.50
答案 0 :(得分:3)
这应该有效
select yourFields
from invoice
inner join cost on cost.item2 = invoice.item1
and cost.date2 = invoice.date1
and cost.time2 = (select max(cost_inner.time2)
from cost as cost_inner
where cost_inner.item2 = invoice.item1
and cost_inner.date2 = invoice.date1
and cost_inner.time2 <= invoice.time1)
有一种方法可以避免内部联接使用更复杂的查询,您可以检查出here