0

我必须运行查询才能找到价格。我有多个价目表,每个价目表都有自己的表。customer_price、default_price 和 minimum_price。

并非所有价目表都包含所有产品,有时产品可能不会出现在任何价目表上,然后价格需要为价格返回 0。

所以我想:

select price from customer_price where customer='walmart' and product='whitebread'

如果这返回结果,那么一切都很好。如果结果为 0,NULL 或查询不返回任何行,我希望它运行:

select price from default_price where customer='walmart' and product='whitebread'

如果这返回结果,那么一切都很好。如果结果为 0,NULL 或查询不返回任何行,我只想返回 0。

我不确定如何进行。我尝试了一个 case 语句,但如果在结果中找不到任何行,case 语句就会失败。我该怎么做或说if 0 results then

预先感谢,一如既往。

4

3 回答 3

4
select top 1 price from (
    select 1 as qorder, price from customer_price where price > 0 and customer='walmart' and product='whitebread'
    union
    select 2 as qorder, price from default_price where price > 0 and customer='walmart' and product='whitebread'
    union 
    select 3 as qorder, 0 
    ) as sq
order by qOrder
于 2013-09-19T09:53:42.970 回答
2
case when
(select count(price) from customer_price where customer='walmart' and product='whitebread' and price is not null and price > 0) > 0 
then 
    select price from customer_price where customer='walmart' and product='whitebread'
else 
    select price from default_price where customer='walmart' and product='whitebread'   
end 
于 2013-09-19T09:54:17.670 回答
0

我正在编写一个双向解决方案,其中包括Empty Select QueriesTables您可以替换您的查询

if OBJECT_ID('tempdb..#temp1') is not null
drop table #temp1

select * into #temp1 from (select col1, col2 from First_Table) as firstTableVariable
if (@@ROWCOUNT > 0)
    begin
    print 'data is displayed from the first table/query'
        select * from #temp1 
    end
else
    begin
    print 'Data displayed from second table/query '
    select col1, col2 from second_Table 
    end
end
于 2017-08-24T11:23:45.857 回答