I am writing a query i should show the records according to the rank position given along with price order and group by sitename
shopdetails
id | productid | productname | sitename | siteid | site_priority | price | color
1 555 xyz a 1 0 10 blue
2 555 xyz b 12 1 50 blue
3 555 xyz a 1 0 12 red
4 555 xyz c 3 4 9 red
5 555 xyz e 15 5 19 blue
6 555 xyz e 15 5 21 red
7 555 xyz b 12 1 42 red
8 555 xyz c 3 4 56 blue
Three conditions i have to do for getting expected output Conditions
- if site_priority !=0 then put that record in that position. Say Eg. if the site_priority = 5 . show that record in fifth position after grouping all the sitename
- Show records price asc if site_priority = 0
- group the records by sitename and sort them by price
Final Expected Output
id | productid | productname | sitename | siteid | site_priority | price | color
7 555 xyz b 12 1 42 red
2 555 xyz b 12 1 50 blue
############ the above two records are kept in the First Position since site_priority = 1 and ordered by price asc
Now check for site_priority 2 is there if not show site_priority = 0 by price asc ,
Now 2nd records would be
1 555 xyz a 1 0 10 blue
3 555 xyz a 1 0 12 blue
Now check for site_priority 3 is there if not check for site_priority 0 ,
is not then make the priority one level minus .
move site_priority 4 to 3 , 5 to 4 .
4 555 xyz c 3 4 9 red
8 555 xyz c 3 4 56 blue
5 555 xyz e 15 5 19 blue
6 555 xyz e 15 5 21 red
Is there any best way to do this complicated Query .
i tired doing like this but it is not coming as i expected.
select
productid,
productname,
sitename,
site_priority,
price,
colorname,
(select
count(*)
from
shopdetails b
where
productid = 1250 and b.site_priority > a.site_priority order by price asc)+1 as rnk
from
shopdetails a
where
productid = 1250
having site_priority > 0
order by rnk
Easy to understand my first condition
sitename | priority
a 1
b 2
c 3
d 0
e 0
f 0
g 0
h 0
i 5
outpt
a 1 ==> position 1
b 2 ==> position 2
c 3 ==> position 3
d 0 ==> position 4
i 5 ==> position 5
e 0 ==> position 6
f 0 ==> position 7
g 0 ==> position 8
h 0 ==> position 9