我有一个包含3列“ID”,“Cost”,“MaxCost”的临时表。下面是我的select语句,它选择给定特定ID的行..
SELECT
t.Cost
t.MaxCost
FROM @temp t
WHERE t.ID = @ID
如何修改上述查询,以便即使给定ID不存在,它仍然会输出Cost = 0& MaxCost = 0
答案 0 :(得分:2)
选择实际和默认记录,然后按权重选择第一个排序。
select top (1)
Cost,
MaxCost
from (
SELECT
t.Cost
t.MaxCost,
1 as takeme
FROM @temp t
WHERE t.ID = @ID
union all
select 0, 0, 0
) foo
order by
foo.takeme desc
答案 1 :(得分:0)
declare @table table (cost int);
insert into @table values (2), (2), (3);
declare @findCost int = 1;
select * from @table where cost = @findCost
union all
select 0 as cost from @table where cost = @findCost having count(*) = 0;
set @findCost = 2;
select * from @table where cost = @findCost
union all
select 0 as cost from @table where cost = @findCost having count(*) = 0;