Sql Server Where Clause If else

jewel 1,206 Reputation points
2022-06-19T14:20:32.77+00:00

Below is a brief outline of one of my queries. Here I am showing stocks without 0. If Purchases_Qty are> 0, Sales_Qty are> 0 and Stocks are = 0 then I can't see that row. It becomes hidden.
My requirement is - if the purchases_Qty are> 0 or sales_Qty> 0, then the stock = 0 will show it. And if Purchases_Qty = 0 and Sales_Qty = 0, then the stock will be <> 0
Thanks in advance to the experienced collaborators.

with Cte as( select
a.Date,
a.Company_Name,
a.Product_Code,
a.Product_Name,
isnull(a.purchase,0) as purchase_Qty,
isnull(b.Sale,0) as Sale_Qty,
stock=isnull(a.purchase,0)-isnull(b.Sale,0)
from
(select Date, Company_Name,Product_Code,Product_Name,sum(isnull(Qty,0)) as purchase from tbl_purchase
group by Date, Company_Name,Product_Code,Product_Name) a
left join
(select Date, Company_Name,Product_code,Product_Name,SUM(isnull(Qty,0)) as Sale from tbl_sales
group by Date, Company_Name,Product_code,Product_Name) b
on a.Company_Name=b.Company_Name
and a.Product_Code=b.Product_code
and a.Product_Name=b.Product_Name
and a.Date=b.Date

)
select Date,Company_Name,Product_Code,Product_Name,purchase_Qty,Sale_Qty,stock from cte
where Date between '2022-04-21' and '2022-04-21'
and stock<>0

Developer technologies | Transact-SQL
SQL Server | Other
{count} votes

Accepted answer
  1. Erland Sommarskog 121.8K Reputation points MVP Volunteer Moderator
    2022-06-19T16:42:02.733+00:00

    Sound like you should change

       and stock <> 0  
    

    to

       and (purchaes_Qty > 0 or Sales_Qty > 0 or stock <> 0  
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.