select * into #table1 from (
select
49 rowid, 7373194 id, 3 ProdType, 200 Amount , 180 Qty union all select
49 , 106049 , 2 , 0 , 180 union all select
1096 , 5008960 , 1 , 0 , 120 union all select
1096 , 108891 , 2 , 0 , 120 union all select
1096 , 6627903 , 1 , 0 , 250 union all select
1096 , 109697 , 3 , 0 , 2500 union all select
927 , 109946 , 2 , 0 , 25 union all select
927 , 109927 , 2 , 0 , 128 union all select
927 , 109927 , 3 , 0 , 25 )B
select * from (
select a.*, Rank() over (Partition BY a.rowid order by
case when (a.amount <> 0 and a.prodtype=3)then 0 else a.amount end,
case when (a.Qty <> 0 and a.prodtype=2)then 0 else a.QTY end,
a.Prodtype DESC) as rankid
from #table1 a)b
--where rankid =1
order by rowid,rankid
result from query above:
rowid id ProdType Amount Qty rankid
49 106049 2 0 180 1
49 7373194 3 200 180 2
927 109946 2 0 25 1
927 109927 2 0 128 1
927 109927 3 0 25 3
1096 108891 2 0 120 1
1096 5008960 1 0 120 2
1096 6627903 1 0 250 3
1096 109697 3 0 2500 4
result needed
rowid Id ProdType Amount Qty Rank
49 7373194 3 200 180 1
49 106049 2 0 180 2
927 109927 2 0 128 1
927 109946 2 0 25 2
927 109927 3 0 25 3
1096 108891 2 0 120 1
1096 109697 3 0 2500 2
1096 5008960 1 0 250 3
1096 6627903 1 0 120 4
If ProdType=3 and amount not 0 then Rank with Highest amount
If ProdType=3 and amount =0 then ProdType 2 with highest Qty
select
49 rowid, 7373194 id, 3 ProdType, 200 Amount , 180 Qty union all select
49 , 106049 , 2 , 0 , 180 union all select
1096 , 5008960 , 1 , 0 , 120 union all select
1096 , 108891 , 2 , 0 , 120 union all select
1096 , 6627903 , 1 , 0 , 250 union all select
1096 , 109697 , 3 , 0 , 2500 union all select
927 , 109946 , 2 , 0 , 25 union all select
927 , 109927 , 2 , 0 , 128 union all select
927 , 109927 , 3 , 0 , 25 )B
select * from (
select a.*, Rank() over (Partition BY a.rowid order by
case when (a.amount <> 0 and a.prodtype=3)then 0 else a.amount end,
case when (a.Qty <> 0 and a.prodtype=2)then 0 else a.QTY end,
a.Prodtype DESC) as rankid
from #table1 a)b
--where rankid =1
order by rowid,rankid
result from query above:
rowid id ProdType Amount Qty rankid
49 106049 2 0 180 1
49 7373194 3 200 180 2
927 109946 2 0 25 1
927 109927 2 0 128 1
927 109927 3 0 25 3
1096 108891 2 0 120 1
1096 5008960 1 0 120 2
1096 6627903 1 0 250 3
1096 109697 3 0 2500 4
result needed
rowid Id ProdType Amount Qty Rank
49 7373194 3 200 180 1
49 106049 2 0 180 2
927 109927 2 0 128 1
927 109946 2 0 25 2
927 109927 3 0 25 3
1096 108891 2 0 120 1
1096 109697 3 0 2500 2
1096 5008960 1 0 250 3
1096 6627903 1 0 120 4
If ProdType=3 and amount not 0 then Rank with Highest amount
If ProdType=3 and amount =0 then ProdType 2 with highest Qty