Reputation: 1564
I have my table with the below fields.
id,user_id,shipping_type,inv_type,invoice_no.
inv_type is ENUM (local/international).
i want to get the invoice no of each row. if inv_type = 'local' then i want invoice_no to have 'local_inv_no' as alias , and if international then 'int_inv_no' as alias. If either is Null then i would want 'local_inv_no' as null or int_inv_no as null in the result,
Below is my latest attempt.
$sql = "select case when b.inv_type='local'
then (case when b.invoice_no is NULL then 'n' else b.invoice_no end 'local_inv')
else
when n.inv_type='int' then (case when b.invoice_no is NULL then 'n' else b.invoice_no end 'int_inv')
end 'inv_status'
from user_invoice b
where b.user_id = '$active_id'
";
But it doesnt seem to give me the result.
Upvotes: 0
Views: 471
Reputation: 51868
I understood your question like you want to have 2 columns, right? Then don't put it in one case when
, cause this results in one column.
select
if(b.inv_type='local', coalesce(b.invoice_no, 'n'), NULL) as local_inv_no,
if(b.inv_type='international', coalesce(b.invoice_no, 'n'), NULL) as int_inv_no
from user_invoice b
where b.user_id = '$active_id'
The coalesce()
function is a short form of your case when
construct. It simply returns the first of its parameters which is not null
.
The if()
is also a little less to write than case when
, as its parameters are if(<what_to_check>, <then>, <else>)
.
Upvotes: 3
Reputation: 60
Looks much alike mixed up statement.
Since i downt know what you try to acommplisch, i try my best to reconstruct a working Statement
select
case when b.inv_type='local'
then (
case when b.invoice_no is NULL
then
'n'
else
b.invoice_no
end)
else
(
case when n.inv_type='int'
then
(
case when b.invoice_no is NULL
then
'n'
else
b.invoice_no
end
)
end
)
end
from user_invoice b
where b.user_id = '$active_id'
i cant figure out why u have 'inv_status' and 'int_inv' in your statement. But that would be a fully working SQL Statement as checked with Mimer SQL
Upvotes: 0