【问题标题】:SQL, how to find the maximum time in column A that is < the time in column B of the current rowSQL,如何在A列中找到<当前行B列中的时间的最大时间
【发布时间】:2012-06-24 16:19:28
【问题描述】:

我在为我认为直截了当的解决方案寻找解决方案时遇到了问题。这是我正在尝试做的一个示例。

TABLE A  
time  |  state  
10:00 |   up  
10:09 |  down  
10:12 |   up  

TABLE B  
time  |  data  
10:05 |  abc  
10:07 |  def  
10:11 |  ghi  

我想加入表 A 和 B 维护 B 中的所有数据,类似于

SELECT tableB.time, tableB.data, tableA.status  
INTO my_results  
FROM tableB  
LEFT JOIN tableA  
WHERE tableB.time > (MAX(tableA.time) < tableB.time)  

所以 my_results 表如下所示:

TABLE my_results  
time  |  data  | state  
10:05 |  abc   |  up  
10:07 |  def   |  up  
10:11 |  ghi   | down  

表A结构

来源,varchar
目的地,varchar
时间,日期时间
状态,varchar

表 B 结构
时间戳,日期时间
来源,varchar
目的地,varchar

这是相关信息。希望这会有所帮助。

【问题讨论】:

  • 您使用的是哪个数据库?

标签: sql time comparison max


【解决方案1】:

以下是 SQL Server 的解决方案:

select  b.time
,       b.data
,       a.state
from    B
outer apply
        (
        select  top 1 *
        from    A
        where   A.time < B.time
        order by
                A.time desc
        ) as A

Live example at SQL Fiddle.

【讨论】:

  • 接下来我会尝试这个,但请耐心等待,我是一个真正的新手。感谢您的快速回复!
猜你喜欢
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 2022-11-14
  • 2012-01-08
  • 2014-04-18
  • 2017-06-05
  • 1970-01-01
相关资源
最近更新 更多