我有两个包含开始和结束日期的SQL表。
Table 1: Name, AddedDate
Table 2: Name, RemovedDate
我正在寻找加入这两个表并将数据转储到临时表中,以显示何时添加名称和从列表中删除名称。
可能多次添加和删除相同的名称。
期望的输出示例
- Name, AddedDate, RemovedDate
- Jane, 2017-02-01, 2017-02-03
- Bill, 2017-01-28, (blank)
- Mike, 2017-01-15, 2017-01-19
- Jane, 2017-01-13, 2017-01-14
有人可以帮忙吗?谢谢。
答案 0 :(得分:3)
另一个选项是 OUTER APPLY (如果是SQL Server)
示例强>
Declare @Table1 table (Name varchar(25),AddedDate date)
Insert Into @Table1 Values
('Jane', '2017-02-01'),
('Bill', '2017-01-28'),
('Mike', '2017-01-15'),
('Jane', '2017-01-13')
Declare @Table2 table (Name varchar(25),RemovedDate date)
Insert Into @Table2 Values
('Jane', '2017-02-03'),
('Mike', '2017-01-19'),
('Jane', '2017-01-14')
Select A.Name
,A.AddedDate
,B.RemovedDate
From @Table1 A
Outer Apply (
Select RemovedDate=min(RemovedDate)
From @Table2
Where Name=A.Name
and RemovedDate>=A.AddedDate
) B
<强>返回强>
Name AddedDate RemovedDate
Jane 2017-02-01 2017-02-03
Bill 2017-01-28 NULL
Mike 2017-01-15 2017-01-19
Jane 2017-01-13 2017-01-14
答案 1 :(得分:1)
使用相关子查询仅考虑最后一次添加名称(并可能删除)......
select Name,
AddedDate,
(select max(RemovedDate)
from table_2
where Name=q1.Name
and RemovedDate >= q1.AddedDate) as RemovedDate
from (select Name,
max(AddedDate) as AddedDate
from table_1
group by name) as q1
order by AddedDate desc,
Name;
每次添加和删除名称时都会显示相同的相关子查询方法......
select Name,
AddedDate,
(select min(RemovedDate)
from table_2
where Name=q1.Name
and RemovedDate >= t1.AddedDate) as RemovedDate
from table_1 t1
order by AddedDate desc,
Name;
答案 2 :(得分:0)
您可以在名称上使用左连接
select t1.name, t1.AddedDate, t2.RemovedDate
from table1 t1
left join table2 t2 on t1.name = t2.name
order by name, t1.AddedDate, t2.RemovedDate
答案 3 :(得分:0)
对于SQL Server使用以下脚本
;WITH CTE
AS
(
SELECT
SeqNo = ROW_NUMBER() OVER(PARTITION BY T1.Name ORDER BY T1.AddedDate DESC,T2.RemovedDate DESC)
T1.Name,
T1.AddedDate,
T2.RemovedDate
FROM Table1 T1
LEFT JOIN Table2 T2
ON LTRIM(RTRIM(T1.name)) = LTRIM(RTRIM(T2.name))
)
SELECT
*
FROM CTE
WHERE SeqNo = 1
如果您想要名称的所有记录,例如多次添加和删除名称并且您想要每个日期,那么只需执行
WHERE SeqNo = 1
部分