2015-12-18 31 views
0

我有一个临时表,包含3列“ID”,“成本”,“MaxCost”..下面是我的选择语句,它选择给定特定ID的行。TSQL:如何输出记录,即使条件不匹配

 SELECT 
      t.Cost 
      t.MaxCost 
     FROM @temp t 
     WHERE t.ID = @ID   

如何修改上面的查询,这样即使给定的ID不符合成本= 0 & MaxCost = 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 
+0

你的答案基于我question..but是正确的,我认为它不会对我想要做的工作.. – LP13

+0

@ user3862378如何这是正确的,当规定的问题是记录 - 复数? – Paparazzi

+0

@Frisbee由于多行在这个问题的背景下没有意义,因此被忽略为一个错字。 [你的回答](http://stackoverflow.com/a/34364467/11683)可以说没有什么意义。 OP实际[意图提问](http://meta.stackexchange.com/q/66377/147640)是[this](http://stackoverflow.com/q/34364484/11683)。 – GSerg

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; 
相关问题