Link to home
Start Free TrialLog in
Avatar of pmessana
pmessana

asked on

MYSQL Conditional Order By with Union

I have a table that has BayNumber, ShelfNumber and ShelfPosition.  When the BayNumber is odd it needs to sort that grouping one way, when the BayNumber is even it needs to sort that grouping another way.

I have tried to accomplish this by using a UNION ALL and having one query return all the EVEN rows and another all the ODD, sorting them correctly in each individual SELECT statement.  I have confirmed that each SELECT is working as intended.

When I mash the two together and attempt to do a GLOBAL order by the BayNumber it does the global but the individual query order is not maintained.  Here is the gist of the query to help.

I have tried some CASE statements in the global order but that isn't respecting the order of the individual.

It should return the following when correct

Bay | Shelf | Position
1 | A | 2
1 | A | 4
2 | A | 15
2 | A | 2

The Bay number needs to drive the Position order.

Hopefully that makes sense to all you experts, I am by far not a SQL expert and this one has me stumped.
(SELECT *, MOD(BayNumber,2) as EvenOdd
FROM orderdetails a
WHERE a.prodtype != 'P'
GROUP BY detailsId, detailproductid, detailoption1 
HAVING EvenOdd=0
ORDER BY BayNumber, ShelfNumber, ShelfPosition ASC
)
 
 
UNION ALL
 
(SELECT *, MOD(BayNumber,2) as EvenOdd
FROM orderdetails a
WHERE a.prodtype != 'P'
GROUP BY detailsId, detailproductid, detailoption1 
HAVING EvenOdd=1
ORDER BY BayNumber, ShelfNumber, ShelfPosition DESC
)
 
ORDER BY BayNumber

Open in new window

Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

>It should return the following when correct
based no what input data?

your SQL is a bit violating some sql rules, "unfortunately" mysql works a bit differently that other sql databases...
ASKER CERTIFIED SOLUTION
Avatar of racek
racek
Flag of Sweden image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pmessana
pmessana

ASKER

Angellll I cut some of the query out.  The point is, there are three columns, BayNumber, ShelfNumber, ShelfPosition.

Racek - brilliant!  I didn't think to turn it negative and keep the same sort going, you got rid of my Union!!!
Awesome answer, so much easier than what I was trying.