比较2本不同书籍中的时间列并获得记录数

时间:2017-07-06 10:44:20

标签: sql

我是SQL的新手,我正在尝试查找同一ship_name的记录数。以下是我当前数据的示例。

第1册

time_column_1   ship_name   ship_arrival_time number_of_records
27/3/2017  4:00  TOMY          28/3/2017 8:00        0
27/3/2017  8:00  TOMY          28/3/2017 8:00        3
27/3/2017  12:00 TOMY          28/3/2017 8:00        4
27/3/2017  16:00 TOMY          28/3/2017 8:00        7
27/3/2017  16:00 HX            28/3/2017 8:00        0

第二册

arrival_time_of_containers   ship_name
27/3/2017 6:00                TOMY
27/3/2017 7:00                TOMY
27/3/2017 8:00                TOMY
27/3/2017 10:00               TOMY
27/3/2017 13:00               TOMY
27/3/2017 13:00               TOMY

以上是我拥有的2本书的数据示例。我试图将第2册中的arrival_time_of_container与第1册中的time_column_1进行比较,并尝试获取number_of_records_column。

number_of_records_column不应该增加,直到arrival_time_of_container列与time_column_1匹配,之前得到所有记录。

你有什么建议吗?

SELECT distinct ship_name, ship_arrival_time, time_column_1, arrival_time_of_containers, count(case when arrival_time_of_containers <= time_column_1 AND ship_name = ship_name then 1 else 0 end) as number_of_records
from [Book1] p
INNER JOIN [Book2] ON p.primary_key = [Book2].primary_key
group by p.ship_name, p.ship_arrival_time, p.time_column_1, [Book2].arrival_time_of_containers
order by p.time_column_1 asc

到目前为止,我已经提出了这一堆代码,但是number_of_records列的值仍然不合适,它根据我的想法不计算。

这是我迄今为止的结果。

ship_name   ship_arrival_time     time_column_1   
          
  TOMY      2017-03-23 14:05:00	2017-03-23 12:00:00
  TOMY      2017-03-23 14:05:00	2017-03-23 12:00:00
  TOMY      2017-03-23 14:05:00	2017-03-23 12:00:00
  TOMY      2017-03-23 14:05:00	2017-03-23 12:00:00
  TOMY      2017-03-23 14:05:00	2017-03-23 12:00:00        
  
  arrival_time_of_containers  number_of_records
    2017-03-21 15:13:00	              5
    2017-03-21 15:22:00	              5
    2017-03-21 15:30:00	              5
    2017-03-21 16:02:00	              5
    2017-03-21 16:13:00	              5

0 个答案:

没有答案