I am trying to run a query in sql_server
I want to join 2 col and compare quantity of both & print_col for which 1st table(sid) has less quantity than 2nd table(idt)
Since I need all data of 1st table irrespective of no join, that's why I am using LEFT JOIN and making null field to 0
SELECT sid.id, sid.total_quantity, idt.id,
CASE
WHEN idt.total_quantity IS NULL THEN 0
ELSE idt.total_quantity
END as total_quantity2
FROM abc_details as sid
LEFT JOIN (SELECT * FROM def_details WHERE location_name = 'XYZ') as idt
ON sid.item_no = idt.item_no
WHERE sid.stock_invoice_id = 37
ORDER BY sid.item_code, sid.lot_number
That is working fine with case condition's col_name 'total_quantity2'
But, when I try to compare
WHERE sid.stock_invoice_id = 37 AND sid.total_quantity < total_quantity2
But, I am getting error
Unknown column 'total_quantity2' in 'where clause'
WHy this is happeing & how to fix this