你既不希望遊標也不希望/然後爲此。相反,您將使用一系列自連接來獲得這些結果。我也將使用一個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
上面看起來可能看起來很複雜,但它可以更快,並且可以在不更改代碼的情況下輕鬆擴展超過三種狀態。
堆棧溢出不是一個代碼寫入服務;你需要展示你到目前爲止已經嘗試了什麼,哪些沒有成功。就目前而言,這只是一個沒有顯示的努力的要求。 – LittleBobbyTables 2014-10-16 14:31:45
您使用的是什麼RDBMS? – 2014-10-16 14:32:28
我正在使用sql server managment studio,換句話說tsql。非常感謝您的快速週轉 – 2014-10-16 14:35:51