Here total two union binding three queries, first query retrieving records from a virtual table(Inner query) and two simple queries retrieving records from a physical tables.
All three queries making a virtual table named “vertulatable” retrieving all records from “vertualtable” with group by and order by clause.
But the problem is its not doing a proper descending order by final price. Some records retrieved from mediater query has value 150 but showing after 0 or less then 150,but should be top from 0 or less then 150 in resultant records.
SELECT
sum(vertualtable.WyoPrice) as WyoPrice,
sum(vertualtable.normalPrice) as normalPrice,
vertualtable.sbnam,
vertualtable.sbwynum,
if(vertualtable.sbwynum in(25,43),
sum(vertualtable.WyoPrice), sum(vertualtable.normalPrice)) as finalPricePrev,
sum(vertualtable.finalPrice) as finalPrice,
vertualtable.BuilderStatus
FROM (
SELECT sum(vertualtbl.WyoPrice) as WyoPrice,
sum(vertualtbl.normalPrice) as normalPrice,
vertualtbl.sbnam,
vertualtbl.sbwynum,
if(vertualtbl.sbwynum in(25,43),
sum(vertualtbl.WyoPrice), sum(vertualtbl.normalPrice)) as finalPrice,
'Main' as BuilderStatus
FROM(
select
b.sbnam,
b.sbwynum,
'g' as g,
sum(if (s.adjprice > 0, s.adjprice, if (s.price > 0, s.price,
s.estprice))) as normalPrice,
st.forsearchwoy,
SUM(if (st.forsearchwoy = 'Y',
F_offshorePrice(s.topsbwynum, s.hulsbwynum, s.sbwynum, s.adjprice,
s.price, s.estprice, s.pricehulint, s.pricetopint, s.pricehulcons,
s.pricetop, s.priceint, s.pricetht),0)) as WyoPrice
from tblship s
left join tblbuilder b on b.sbwynum = s.sbwynum and b.deleted = 'N'
left join tblshiptype as st on st.wytypid = s.wytypid
where s.deleted != 'Y' and
(s.sbwynum > 0) and
status in ('O', 'FO', 'JV', 'PR', 'C', 'F')
group by s.tblshipwynum
) vertualtbl group by vertualtbl.sbwynum
UNION
select
'0' as WyoPrice,
'0' as normalPrice,
b.sbnam as sbnam,
s.hulsbwynum as sbwynum,
SUM(if (st.forsearchwoy = 'Y',s.pricehulcons,0)) as finalPrice,
'HUL' as BuilderStatus
from tblship s
left join tblbuilder b on b.sbwynum = s.hulsbwynum and b.deleted = 'N'
left join tblshiptype as st on st.wytypid = s.wytypid
where s.deleted != 'Y' and
(s.sbwynum != s.hulsbwynum and
s.hulsbwynum > 0 ) and
status in ('O', 'FO', 'JV', 'PR', 'C', 'F')
group by s.hulsbwynum
UNION
select
'0' as WyoPrice,
'0' as normalPrice,
b.sbnam as sbnam,
s.topsbwynum as sbwynum,
SUM(if (st.forsearchwoy = 'Y',s.pricetop,0)) as finalPrice,
'TOP' as BuilderStatus
from tblship s
left join tblbuilder b on b.sbwynum = s.topsbwynum and b.deleted = 'N'
left join tblshiptype as st on st.wytypid = s.wytypid
where s.deleted != 'Y' and
(s.sbwynum != s.topsbwynum and
s.topsbwynum > 0 ) and
status in ('O', 'FO', 'JV', 'PR', 'C', 'F')
group by s.hulsbwynum
) as vertualtable
group by vertualtable.sbnam
order by vertualtable.finalPrice desc
Thanks a lot.
I made some small modifications to your query – try to see if the result is the one you expected