按顺序查询多个表中的数据

时间:2016-05-21 05:29:05

标签: sql-server

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

例如:价格表有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中。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 

我认为这是一个有趣的问题,并且知道可以在一个查询中完成。其他答案也很棒!只是加油吧

答案 2 :(得分: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