我想要加入两个表。但是,信息在第一个表中写为。
我的第一张表看起来像这样:
No. | Date | From entry | To Entry |
+---+------------+------------+----------+
1 | 21.12.2013 | 3 | 10
我的第二张表看起来像这样:
| Entry | Code |
+--------+-------+
| 3 | 1 |
| 4 | 0 |
| 5 | 2 |
| 6 | 3 |
| 7 | 1 |
| 8 | 0 |
| 9 | 6 |
| 10 | 1 |
我想根据from到信息加入两者。结果应如下所示:
| Entry | Code | Date |
+--------+-------+------------+
| 3 | 1 | 21.12.2013 |
| 4 | 0 | 21.12.2013 |
| 5 | 2 | 21.12.2013 |
| 6 | 3 | 21.12.2013 |
| 7 | 1 | 21.12.2013 |
| 8 | 0 | 21.12.2013 |
| 9 | 6 | 21.12.2013 |
| 10 | 1 | 21.12.2013 |
我不知道如何使用t-sql实现这一目标。
答案 0 :(得分:2)
您只需要为INNER JOIN
SELECT *
FROM table1
INNER JOIN table2 ON table2.Entry >= table1.[From entry]
AND table2.Entry <= table1.[To entry]
或者如果你想从table1返回所有记录,你可以考虑使用LEFT JOIN
,无论它们是否在table2中有相关记录。
答案 1 :(得分:1)
试试这个:(INNER JOIN
和BETWEEN AND
)
SELECT
Entry, Code, Date
FROM
Table1 T1 INNER JOIN
Table2 T2
ON T2.Entry BETWEEN T1.[From entry] AND T1.[To entry]
答案 2 :(得分:1)
试试这个
Select table2.*,
table1.date
from table2
left join table1 on
table2.entry between table1.fromentry and table1.toentry
答案 3 :(得分:0)
这应该有效
SELECT B.Entry,B.Code,A.Date
FROM Table1 A CROSSJOIN Table2 B
WHERE B.Entry >= A.[From Entry] AND B.Entry <= A.[To Entry]
答案 4 :(得分:0)
SELECT Entry, Code, (SELECT T1.Date
FROM FirstTable T1
WHERE T1.Entry BETWEEN T2.[From Entry]
AND T2.[To Entry]) AS Date
FROM SecondTable T2