sql server - T-SQL cursor or if or case when -



sql server - T-SQL cursor or if or case when -

i have table:

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

result output should this:

quotid itration qstatus ------------------------------ 5329 3 sold 4329 2 sold 3214 2 inreview

t-sql query, want info within "sold" status if not there "inreview" if not there "assigned" , @ same time if "sold" or "inreview" or "assigned" has multiple iteration want highest "iteration".

please help me, in advance :)

you want neither cursors nor if/then this. instead, you'll utilize series of self-joins these results. i'll utilize cte simplify getting max iteration @ each step:

with statusiterations ( select quotid, max(itration) iteration, qstatus table_name_a grouping quotid, qstats ) select q.quotid, coalesce(sold.iteration,rev.iteration,asngd.iteration) iteration, coalesce(sold.qstatus, rev.qstatus, asngd.qstatus) qstatus --initial pass list of quotes, ensure every quote included in results (select distinct quotid table_name_a) q --one additional pass each possible status left bring together statusiterations sold on sold.quotid = q.quotid , sold.qstatus = 'sold' left bring together statusiterations rev on rev.quotid = q.quotid , rev.qstatus = 'inreview' left bring together statusiterations asngd on asngd.quotid = q.quotid , asngd.qstatus = 'assigned'

if have table equates status numeric value, can farther improve on this:

table: status

qstatus sequence 'sold' 3 'inreview' 2 'assigned' 1

and code becomes:

select t.quotid, max(t.itration) itration, t.qstatus ( select t.quotid, max(s.sequence) sequence table_name_a t inner bring together status s on s.qstatus = t.qstatus grouping t.quotid ) seq inner bring together status s on s.sequence = seq.sequence inner bring together table_name_a t on t.quotid = seq.quotid , t.qstatus = s.qstatus grouping t.quoteid, t.qstatus

the above may complicated @ first, can faster , scale beyond 3 statuses without changing code.

sql sql-server

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -