![](/img/trans.png)
[英]How can i join two tables with two columns that refers the same column in the second table in SQL Server
[英]SQL Server: How to select column from two tables and show the same value of the closest date from the second table
我懷疑你可能想要這樣的東西
SELECT
t1.id,
t1.[value] AS [table1],
t1.[date],
(
SELECT TOP 1 t2.[value]
FROM [Table2] t2
WHERE t2.[date] < t1.[date]
ORDER BY t2.[date] DESC
) AS [table2]
FROM [Table1] t1;
在子查詢中,它應該是t2.[date] < t1.[date]
還是t2.[date] <= t1.[date]
我會根據具體情況由您決定兩個表之間的日期/時間匹配。
您可以嘗試按如下方式正確加入
SELECT dbo.Table1.id, dbo.Table1.value1 as 'table1', dbo.Table2.date, dbo.Table2.value
FROM
dbo.Table1
Right JOIN dbo.Table2 ON
dbo.Table1.date = dbo.Table2.date
請注意,這只是一個示例。 您應該添加 2 個表,每個表具有 1 個相同的主鍵,並且具有相同數量的主鍵
不清楚 table2 的行應該放在 table 1 的相應行旁邊的依據是什么? 例如,為什么要將表 2 的 id 1 放在表 1 的 id 1 和 2 上? 同樣,為什么表 2 的 id 2 與表 1 的 id 3、4、5、6 相對應?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.