我在Sql Server 2008中有两个表 - > SchedulePermanent和ScheduleImported
SchedulePermanent:
Id StartDate EndDate值
1 01-01-2013 03-01-2013 100
2 03-01-2013 07-01-2013 200
3 07-01-2013 18-01-2013 300
CheduleImported:
Id StartDate EndDate值
1 01-01-2013 04-01-2013 100
2 04-01-2013 06-01-2013 200
3 06-01-2013 15-01-2013 300
4 15-01-2013 18-01-2013 100
我想在结果表中只插入每天两个时间表中不相等的值。
例子:( OldValue:出现在永久表中,NewValue出现在导入表中)
日期OldValue NewValue
03-01-2013 200 100
06-01-2013 200 300
15-01-2013 300 100
16-01-2013 300 100
17-01-2013 300 100
18-01-2013 300 100
我是否必须按日期拆分临时表中的每个表,然后对每个日期进行比较还是有更好的方法? (我看到一些话题谈论交叉连接,但我从未使用过它)
谢谢,
答案 0 :(得分:0)
我认为你不需要交叉连接,你应该只需要一个内部连接即可。
select Date, SchedulePermanent.Value as OldValue, ScheduleImported.AsNewValue
from SchedulePermanent
join ScheduleImported on SchedulePermanent.StartDate = ScheduleImported.StartDate and SchedulePermanent.Value <> ScheduleImported.Value
但是,这仅适用于导入SchedulePermanent中已存在的日期的值。要包含永久不存在的导入值,它将如下所示:
select Date, SchedulePermanent.Value as OldValue, ScheduleImported.AsNewValue
from SchedulePermanent
right join ScheduleImported on SchedulePermanent.StartDate = ScheduleImported.StartDate
where SchedulePermanent.StartDate is null
如果要覆盖这些值,则可以签出合并语句。
MERGE SchedulePermanent AS target
USING (SELECT StartDate, Value from ScheduleImported) AS source
ON (target.StartDate = source.StartDate)
WHEN MATCHED THEN
UPDATE SET Value = source.Value
WHEN NOT MATCHED THEN
INSERT (StartDate, Value)
VALUES (source.StartDate, source.Value)
答案 1 :(得分:0)
您获取所有不平等记录的简单方法:
SELECT S.ID, S.StartDate, S.Value
FROM SchedulePermanent AS S
WHERE S.Value NOT EXSIST(
SELECT VALUE
FROM CheduleImported AS C
WHERE C.StartDate = S.StartDate AND C.EndDate = S.EndDate
)