T-SQL游标或if或case何时

时间:2014-10-16 14:28:28

标签: sql sql-server

我有这张桌子:

Table_NAME_A

quotid  itration   QStatus            
--------------------------------
 5329    1           Assigned                                   
 5329    2           Inreview                                   
 5329    3           sold                                           
 4329    1           sold                     
 4329    2           sold                     
 3214    1           assigned                
 3214    2           Inreview  

结果输出应如下所示:

quotid  itration    QStatus  
------------------------------          
 5329    3           sold                       
 4329    2           sold                     
 3214    2           Inreview

T-SQL查询,所以基本上我想要"出售"状态如果没有那么" inreview"如果没有那么"分配"如果"出售"同时也是或" inreview"或者"分配"有多次迭代然后我想要最高的#34;迭代"。

请帮助我,提前谢谢:)

2 个答案:

答案 0 :(得分:1)

这是优先级查询。一种方法是在union all

中进行连续比较
select a.*
from table_a a
where quote_status = 'sold'
union all
select a.*
from table_a a
where quote_status = 'Inreview' and
      not exists (select 1 from table_a a2 where a2.quoteid = a.quoteid and a2.quotestatus = 'sold')
union all
select a.*
from table_a a
where quote_status = 'assigned' and
      not exists (select 1
                  from table_a a2
                  where a2.quoteid = a.quoteid and a2.quotestatus in ('sold', 'Inreview')
                 );

要获得更大数据集的性能,您需要table_a(quoteid, quotestatus)上的索引。

答案 1 :(得分:0)

你既不想要游标,也不希望这样做。相反,您将使用一系列自连接来获得这些结果。我还将使用CTE来简化每一步的最大迭代次数:

with StatusIterations As 
(
    SELECT quotID, MAX(itration) Iteration, QStatus
    FROM table_NAME_A
    GROUP BY quotID, QStats
)
select q.quotID, coalesce(sold.Iteration,rev.Iteration,asngd.Iteration) Iteration,
                coalesce(sold.QStatus, rev.QStatus, asngd.QStatus) QStatus 
from
  --initial pass for list of quotes, to ensure every quote is included in the results
  (select distinct quotID from table_NAME_A) q
 --one additional pass for each possible status
left join StatusIterations sold on sold.quotID = q.quotID and sold.QStatus = 'sold'
left join StatusIterations rev on rev.quotID = q.quotID and rev.QStatus = 'Inreview'
left join StatusIterations asngd on asngd.quotID = q.quotID and asngd.QStatus = 'assigned'

如果您的表格将状态等同于数值,则可以进一步改进:

表:状态

QStatus   Sequence
'Sold'      3
'Inreview'  2
'Assigned'  1 

代码变为:

select t.quotID, MAX(t.itration) itration, t.QStatus
from
(
    select t.quotID, MAX(s.Sequence) As Sequence
    from table_NAME_A t
    inner join Status s on s.QStatus = t.QStatus
    group by t.quotID
) seq
inner join Status s on s.Sequence = seq.Sequence
inner join table_NAME_A t on t.quotID = seq.quotID and t.QStatus = s.QStatus
group by t.quoteID, t.QStatus

上面看起来可能看起来很复杂,但它可以更快,并且可以在不改变代码的情况下轻松扩展到三种状态。