我有一张桌子,里面有一些ids,比如-
id
o1
o2
o3现在,另一个表包含基于国家的这些ids的价格,如
id country price
o1 IND 11
o1 US 10
o1 default 9
o2 default 2
o3 UK 4
o3 default 3基本上,我必须编写一个存储过程,其中我将把区域作为参数传递。例如,如果region是UK,那么我希望按下面的方式选择行,如果有匹配,则选择该行,否则为默认行。
id country price
o1 default 9
o2 default 2
o3 UK 4请您提出一种好的、高效的SQL书写方法。
发布于 2016-04-06 00:13:37
将CROSS APPLY与TOP结合使用
DECLARE @country VARCHAR(20) = 'UK'
SELECT x.*
FROM tblId i
CROSS APPLY(
SELECT TOP 1 *
FROM tblPrice p
WHERE
p.id = i.id
AND (p.country = @country OR p.country = 'default')
ORDER BY
CASE
WHEN p.country = 'default' THEN 1
ELSE 0
END
)x发布于 2016-04-06 00:13:08
一种方法使用两个left join:
select ids.id, coalesce(p.country, d.country) as country,
coalesce(p.price, d.price) as price
from ids left join
prices p
on ids.id = p.id and p.country = @country left join
prices d
on d.country = 'default';我认为更有趣的方法是使用cross apply
select p.*
from ids cross apply
(select top 1 p.*
from prices p
where p.id = ids.id and p.country in (@country, 'default')
order by (case when p.country = @country then 1 else 2 end)
) p;https://stackoverflow.com/questions/36439186
复制相似问题