0

我有两张桌子:

  1. 发票
  2. 成本

我想找到与发票记录关联的成本记录来创建利润报告。

例如,从发票表中订购 1004,我想从该文件中获取日期和时间,并根据该日期和时间(等于或小于那时)找到成本。

订单 1004 的 04/15 时间为 171543,它将链接日期为 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 
4

1 回答 1

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)

有一种方法可以避免使用更复杂的查询进行内部连接,您可以在此处查看

于 2012-04-25T15:06:25.857 回答