表1
ID Date
001 01/02/2009
001 02/02/2009
...
...
001 28/02/2009
002 01/02/2009
002 02/02/2009
...
...
002 28/02/2009
表2
ID Date Salary
001 02/02/2009 800
001 25/02/2009 500
002 01/02/2009 300
...,
我想加入两个表
尝试查询
SELECT table1.id, table1.date, table2.salary
FROM table1
LEFT OUTER JOIN table2 ON
table1.id = table2.id AND table1.date = table2.date
结果
Id Date Salary
001 02/02/2009 800
001 25/02/2009 500
002 01/02/2009 300
我想显示一个结果,比如所有id,table1中的日期和table2中的工资,其中table1.date = table2.date
预期产出
ID Date Salary
001 01/02/2009
001 02/02/2009 800
001 03/02/2009
...
...
001 25/02/2009 500
...
001 28/02/2009
002 01/02/2009 300
002 02/02/2009
...
...
002 28/02/2009
...
如何在SQL中进行查询
需要查询帮助
答案 0 :(得分:2)
作为测试,我使用了您提供的数据和查询,提供了以下结果。
请注意,由于您提供的数据中没有日期匹配,因此不会返回工资500.
id date salary
----------- ----------------------- -----------
1 2009-02-01 00:00:00.000 NULL
1 2009-02-02 00:00:00.000 800
1 2009-02-28 00:00:00.000 NULL
2 2009-02-01 00:00:00.000 300
2 2009-02-02 00:00:00.000 NULL
2 2009-02-28 00:00:00.000 NULL
DECLARE @Table1 TABLE (ID INTEGER, Date DATETIME)
DECLARE @Table2 TABLE (ID INTEGER, Date DATETIME, Salary INTEGER)
INSERT INTO @Table1 VALUES (001, '02/01/2009')
INSERT INTO @Table1 VALUES (001, '02/02/2009')
INSERT INTO @Table1 VALUES (001, '02/28/2009')
INSERT INTO @Table1 VALUES (002, '02/01/2009')
INSERT INTO @Table1 VALUES (002, '02/02/2009')
INSERT INTO @Table1 VALUES (002, '02/28/2009')
INSERT INTO @Table2 VALUES (001, '02/02/2009', 800)
INSERT INTO @Table2 VALUES (001, '02/25/2009', 500)
INSERT INTO @Table2 VALUES (002, '02/01/2009', 300)
Select table1.id, table1.date, table2.salary
from @table1 table1
left outer join @table2 table2 on table1.id = table2.id and table1.date = table2.date