mysql - How to use case statement in a union -


below part of script.

select a. itemcode, sum(b.quantity) 'y1qty',      isnull(null,0) 'yr2qty', sum(c.amt) 'yr1amt'      isnull(null,0) 'yr2amt', abc left join def b on a.itemcode = b.itemcode group a. itemcode  union  select  a1. itemcode, isnull(null,0) 'yr1qty',     sum(b1.quantity) 'yr2qty', isnull(null,0) 'yr1amt',     sum(c.amt) 'yr2amt'  abc a1 left join def b1 on a1.itemcode = b1.itemcode group a1.itemcode 

table a: sample output (based on query above)

itemcode     y1qty  yr2qty   yr1amt      yr2amt item 001     150      0       200.00       0 item 002      0      300        0         150.00 item 003      0      50         0         100.00 item 004     20      0        150.00       0        

i want insert case statement wherein logic this: if y1qty = 0 , yr2qty = 0 blah blah.. if y1qty = 0 , y2qty > 0 blah blah.. 'diff'

and aiming achieve result:

table b:  itemcode     y1qty  yr2qty   diff      yr1amt      yr2amt item 001     150      0         0        200.00       0 item 002      0      300       100        0         150.00 item 003      0      50        100        0         100.00 item 004     20      0           0      150.00       0  item 005     20      30       1000      100.00      200.00 

you need wrap query subquery , following:

select    itemcode,    y1qty,    yr2qty,    case when y1qty = 0 , yr2qty = 0 ... when ... ... else ... end diff,   yr1amt,   yr2amt (   select a. itemcode, sum(b.quantity) 'y1qty',        isnull(null,0) 'yr2qty', sum(c.amt) 'yr1amt'        isnull(null,0) 'yr2amt',   abc   left join def b on a.itemcode = b.itemcode   group a. itemcode    union    select  a1. itemcode, isnull(null,0) 'yr1qty',       sum(b1.quantity) 'yr2qty', isnull(null,0) 'yr1amt',       sum(c.amt) 'yr2amt'    abc a1   left join def b1 on a1.itemcode = b1.itemcode   group a1.itemcode ) t 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -