2012-04-25 98 views
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 
+1

请让我们知道您正在使用的数据库系统。 – squillman 2012-04-25 14:47:40

+0

不稳定的价格!在60秒内2.50到4.00 ... – 2012-04-25 14:55:13

+0

通过将时间与时间分开,您已经做出了像这样的查询操作,如果您有单一的DATE + TIME(又名TIMESTAMP)列,那么这种查询操作会更加复杂。 – 2012-04-25 15:53:34

回答

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

+0

一般结构是正确的,但我希望答案是基于发票时间1之前的MAX(cost.time2)。由于日期与时间分离,模式变得复杂;这种事通常是一个错误,但不是你的错。 – 2012-04-25 15:52:23

+0

@JonathanLeffler你是对的。固定。随时可以编辑自己! – 2012-04-25 16:14:45