2012-04-25 150 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