2016-05-21 24 views
0

将从多个价格表中检索项目价格。每个项目的价格可能不在所有表格上。查询序列基于表优先级。价格可用时查询将停止。按顺序查询多个表格中的数据

例如:价格表有T1,T2和T3以及表查询顺序,优先级为T1,T2和T3。

T1表记录

Item, Price 
I1, $11 
I3, $13 
I4, $14 

T2表记录

Item, Price 
I2, $21 
I3, $23 
I5, $25 

T3表记录

Item, Price 
I1, $31 
I2, $32 
I6, $33 

结果:

Item I1 is $11, I3 is $13, 
and I4 is $14. 

它将从作为第一优先级表的T1中检索。由于价格在T1中可用,因此不会搜索T2和T3。

项目I2和I5将来自表格T2。
它们在第一优先级表T1中不可用并且查询移动到第二优先级表T2。

项目I6将来自T3。
由于I6不在T1和T2中。

回答

1
; with item as 
(
    select item from T1 
    union 
    select item from T2 
    union 
    select item from T3 
) 
select item = i.item, 
      value = coalesce(v1.value, v2.value, v3.value) 
from  item i 
left join T1 v1 on i.item = v1.item 
left join T2 v2 on i.item = v2.item 
left join T3 v3 on i.item = v3.item 
+0

伟大的解决方案和感谢。 – YellowLarry

1

也许这样?

create table #item1(
    item int, 
    value int 
) 

insert into #item1 values 
(1,1), 
(2,2) 

create table #item2(
    item int, 
    value int 
) 

insert into #item2 values 
(1,10), 
(2,20), 
(3,30) 

create table #item3(
    item int, 
    value int 
) 

insert into #item3 values 
(1,100), 
(2,200), 
(3,300), 
(4,400) 

;with cte as (
    select *, t=1 from #item1 
    union all 
    select *, t=2 from #item2 
    union all 
    select *, t=3 from #item3 
), 
cte1 as (
    select 
     *, 
     rn = row_number() over (partition by item order by t) 
    from 
     cte 
) 
select 
    item, value 
from 
    cte1 
where 
    rn = 1 


drop table #item1 
drop table #item2 
drop table #item3 
+0

结果是正确的。谢谢, – YellowLarry

1

确定,而无需创建表(临时或以其他方式):

select 
M.item --Select unique item from Master list 
,coalesce(
    (select price from T1 where T1.item = M.item), 
    (select price from T2 where T2.item = M.item), 
    (select price from T3 where T3.item = M.item) 
) --Cascade of prices per table 
from 
    (select * from T1 
    union 
    select * from T2 
    union 
    select * from T3) M --Creating Master list of items and prices 
group by item --ensuring that we only pull unique items 

我认为这是一个有趣的问题,并知道它可以在一个查询来完成。其他答案也很棒!只是将它们加起来

+0

不错的尝试。尽管select子句中的子查询不是性能的好主意。检查你的执行计划。 ;-) P.S.在coalesce之前移除''''。 – shadow

+0

结果正是我需要的。附: ','在SQL Server 2014'coalesce'之前是必需的。 – YellowLarry

+0

@YellowLarry原始代码是'select M.item ,, coalesce' – shadow