SQL - 如何连接相似(不精确)的列
我有两个表几乎在同一时间更新 - 我需要加入日期时间列。
我试过这个:
SELECT *
FROM A, B
WHERE ABS(DATEDIFF(second, A.Date_Time, B.Date_Time)) = (
SELECT MIN(ABS(DATEDIFF(second, A.Date_Time, B2.Date_Time)))
FROM B AS B2
)
但它告诉我:
在包含外部引用的聚合表达式中指定多个列。如果正在聚合的表达式包含外部引用,则该外部引用必须是表达式中引用的唯一列。
我如何加入这些表?
I have two tables which get updated at almost the exact same time - I need to join on the datetime column.
I've tried this:
SELECT *
FROM A, B
WHERE ABS(DATEDIFF(second, A.Date_Time, B.Date_Time)) = (
SELECT MIN(ABS(DATEDIFF(second, A.Date_Time, B2.Date_Time)))
FROM B AS B2
)
But it tells me:
Multiple columns are specified in an aggregated expression containing an outer reference. If an expression being aggregated contains an outer reference, then that outer reference must be the only column referenced in the expression.
How can I join these tables?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
怎么样(假设 SQL 2005+):
在我的解决方案中,我使用公共表表达式或简称 CTE。在 CTE 中,我使用排名函数 (
ROW_NUMBER
),它计算 CTE 表达式中的每一行。 ROW_NUMBER 函数将通过按绝对值排序的 PARTITION BY A.DateTime 子句返回为表 A 中的每个 DateTime 值提供一个连续整数A.DateTime
值与B.DateTime
值的“接近度”。因此,我使用 Abs(DateDiff(s,A.DateTime, B.DateTime) 对“紧密度”进行排名,并为每个值选择最高排名(排名 = 1,也称为“最接近”值)A.DateTime
值是否存在平局并不重要,因为ROW_NUMBER()
函数将为每个A.DateTime< 返回一个唯一的数字列表。 /代码> 值。
How about something like (assuming SQL 2005+) :
In my solution, I'm using a common-table expression or CTE for short. In the CTE, I'm using a ranking function (
ROW_NUMBER
) which calculates for each row in the CTE expression. TheROW_NUMBER
function will return provide a sequential integer for eachDateTime
value in table A via thePARTITION BY A.DateTime
clause ordered by the absolute value of the "closeness"A.DateTime
value to theB.DateTime
value. Thus, I'm ranking the "closeness" usingAbs(DateDiff(s,A.DateTime, B.DateTime)
and choosing the highest rank (rank = 1, aka "closest" value) for eachA.DateTime
value. It will not matter if there is a tie as theROW_NUMBER()
function will return a unique list of numbers for eachA.DateTime
value.这是你想要的吗?它将检查 1 秒差异
Is this what you want? It will check for 1 second difference
最好首先创建一个视图,其中包含保存计算出的 datediff 的列,然后从中构造一个查询。
It might be better to first create a view that contains a column holding your computed datediff, and then construct a query from that.