A bit of background. My company has produced an application that takes a SQL query, then uses the values it returns to produce graphs and K.P.I.s. In my problem, we are producing a graph to show the total amount of orders broken down by despatch “route” for a specific formatted date.
There are two tables involved, order header (ORDERS) and items (ITEMS).
The program requires two fields, XAxis and YAxis to be passed to it to produce a graph. The graph we wish to produce has the Route Reference (Text) as the XAxis and a sum of items as the YAxis.
Complications occur with the route. The route can be changed by the operations before despatch, the new route is stored in a different field; lets call these OLDROUTE and NEWROUTE. If NEWROUTE is blank then they are using the OLDROUTE. If NEWROUTE has any value then use NEWROUTE as XAxis.
The date used in our tables is an integer, in the format YYMMDD. The code made to generate it dynamically is given as
@DATE=(((year(curdate())-2000)*10000)+(month(curdate())*100)+(day(curdate())))
This is compared with the field DESPDATE to get all orders completed today.
I have a version that works OK, posted below
select CASE WHEN ORDERS.NEWROUTE='' then substr(ORDERS.OLDROUTE) else substr(ORDERS.NEWROUTE,1,6) end AS XAxis, SUM(ITEMS.QUANTITY) as YAxis
FROM ORDERS
join ITEMS
on ORDERS.ORDNUM=ITEMS.ORDNUM
where
ORDERS.DESPDATE=@DATE
and ORDERS.STATUS='COMPLETE'
group by CASE WHEN ORDERS.NEWROUTE='' then substr(ORDERS.OLDROUTE) else substr(ORDERS.NEWROUTE,1,6) end
order by CASE WHEN ORDERS.NEWROUTE='' then substr(ORDERS.OLDROUTE) else substr(ORDERS.NEWROUTE,1,6) end
This works fine. Now the complications come when they want to use a different field for a specific route. So for example: for route (XAxis) = 'PARCEL' then want to use ORDERS.ISSUEDATE, for route 'BOX' they want to use ORDERS.PACKDATE and for everything else they want it to be the same.
So the new code would be something like:
select CASE WHEN ORDERS.NEWROUTE='' then substr(ORDERS.OLDROUTE) else substr(ORDERS.NEWROUTE,1,6) end AS XAxis, SUM(ITEMS.QUANTITY) as YAxis
FROM ORDERS
join ITEMS
on ORDERS.ORDNUM=ITEMS.ORDNUM
where
CASE WHEN XAxis='PARCEL' then ORDERS.ISSUEDATE=@DATE
ELSE WHEN XAxis='BOX' then ORDERS.PACKDATE=@DATE
else ORDERS.DESPDATE=@DATE end
and ORDERS.STATUS='COMPLETE'
group by CASE WHEN ORDERS.NEWROUTE='' then substr(ORDERS.OLDROUTE) else substr(ORDERS.NEWROUTE,1,6) end
order by CASE WHEN ORDERS.NEWROUTE='' then substr(ORDERS.OLDROUTE) else substr(ORDERS.NEWROUTE,1,6) end
This does not work. IS actually possible to use different table fields in a where clase case statement? Are they asking more than we can deliver?
I have tried a similar query using IF instead of CASE but have not had any success with it.
Just use
ORin some parenthetical filters: