-2

我需要帮助,为以下场景构建 SQL(查询或 CTE)

问题:我需要将我的主表 A 与详细表 B 连接起来,以从表 B 中找出匹配的记录/行(对于表 A 的每条记录),具有相同的 itemType、具有 max(TransactionTime) && TransactionTime < EntryTime 的表 A 中对应的国家/地区记录。

订单表

 id itemType      country     EntryTime   
 1. Item1           IND      12:01:20:291 
 2. Item2           USA      14:11:22:299
 3. Item4           LON      18:01:17:112 
 4. Item1           SIN      20:05:30:020
 5. Item3           HKG      22:02:23:442

股价表

id  itemType      country   TransactionTime   Price
1.  Item1           IND      12:01:20:291     10.12
2.  Item2           USA      14:11:22:299     50.12
3.  Item4           LON      18:01:17:112     02.12
4.  Item1           SIN      20:05:30:020     10.67
5.  Item3           HKG      22:02:23:442     11.22
6.  Item1           IND      12:01:20:291     10.14
7.  Item2           USA      14:11:22:299     50.11
8.  Item4           LON      18:01:17:112     02.10
9.  Item1           SIN      20:05:30:020     10.90
10. Item3           HKG      22:02:23:442     11.37
11. Item1           IND      12:01:20:291     10.10
12. Item2           USA      14:11:22:299     50.01
13. Item4           LON      18:01:17:112     02.11
14. Item1           SIN      20:05:30:020     10.89
15. Item3           HKG      22:02:23:442     11.90

请帮助提供建议,如果需要更多详细信息,请在评论中告诉我

尝试过的解决方案

Select o.id, o.itemType, o.country, o.EntryTime, o.sp.price
from OrderTable o join
     StockPrice sp
     ON o.country = sp.country and o.itemType = sp.itemType and
        o.EntryTime = (select top 1 TransactionTime from StockPrice spIN where o.country = spIN.country and o.itemType = spIN.itemType and 
and spIN.spIN.TransactionTime < o.EntryTime order by spIN.TransactionTime)

不知何故,结果集的行数超过了预期的行数

上述查询的问题..

  1. 从上面的查询中,我只得到表 A 中第一行的结果。
  2. 如果表 B 有超过一行的确切时间为 max TransactionTime,则返回的结果将对应于表 b 中的行数。
4

1 回答 1

0

看看这是否有效:

select o.id, o.itemType, o.country, o.EntryTime, sp.price
from OrderTable o cross apply (
    select top 1 * from StockPrice spIN
    where o.country = spIN.country and o.itemType = spIN.itemType
       and spIN.TransactionTime <= o.EntryTime
    order by TransactionTime desc
) sp
order by id;
于 2020-08-25T19:18:04.900 回答