我有两个类似的表:
表1 - 唯一ID'
ID Date
1 3/8/2017
2 3/8/2017
3 3/8/2017
表2
ID Date SourceID
1 3/8/2017 1
1 3/8/2017 2
1 3/8/2017 3
2 3/8/2017 2
3 3/8/2017 1
3 3/8/2017 3
我想编写一个结果如下的查询:
结果
ID SourceID
1 2
2 2
3 1
源ID排序应为2,1,3
我有:
select Table1.ID
, COALESCE(Join1.SourceID, Join2.SourceID, Join3.SourceID) as SourceID
from Table1
left outer join Table2 Join1
on Table1.date = Join1.date
and Table1.ID = Join1.ID
and Join1.SourceID = 2
left outer join Table2 Join2
on Table1.date = Join2.date
and Table1.ID = Join2.ID
and Join2.SourceID = 1
and Join1.SourceID is null
left outer join Table2 Join3
on Table1.date = Join3.date
and Table1.ID = Join3.ID
and Join3.SourceID = 3
and Join1.SourceID is null
and Join2.SourceID is null
但目前这只是将记录保存在sourceid = 2
并且不会添加到其他源代码中。
提前感谢您的帮助。如果您需要任何澄清,请告诉我。使用SQL-Server。我只需要一些固定数量的源,所以我避免使用游标。
答案 0 :(得分:2)
这是优先级查询。我会用outer apply
:
select t1.*, t2.sourceId
from table1 t1 outer apply
(select top 1 t2.*
from table2 t2
where t2.id = t1.id and t2.date = t1.date
order by (case t2.sourceid when 2 then 1 when 1 then 2 when 3 then 3 end)
) t2;
注意:为了便于阅读,您可以将order by
简化为:
order by charindex(cast(t2.sourceId as varchar(255)), '2,1,3')
如果您对outer apply
感到不舒服,可以使用一个join
做同样的事情:
select t1.*, t2.sourceId
from table1 t1 join
(select t2.*,
row_number() over (partition by id, date
order by (case t2.sourceid when 2 then 1 when 1 then 2 when 3 then 3 end)
) as seqnum
from table2 t2
) t2
on t2.id = t1.id and t2.date = t1.date and t2.seqnum = 1;