Home > front end >  T-SQL - How to select two columns data of same table by grouping and using two different where claus
T-SQL - How to select two columns data of same table by grouping and using two different where claus

Time:10-20

I have orders table with two columns sales_amt, Disc_Amt. I want to find the each month total sales amount having discounts and without discount

Table:

month sales_amt Disc_Amt
Jan 20
Jan 30
Feb 5 2
Feb 30
Feb 10 5
Mar 80 10
Mar 20

Result required:

month Sales_Amount_Without_Discount Sales_Amount_With_Discount
Jan 50 0
Feb 30 15
Mar 80 20

I tried with the below query

Select 
         month(invoice_date),
         sales_amt as Sales_Amount_Without_Discount,
         Sales_Amount_Without_Discount =  (select  
                                                 sales_amt 
                                           from 
                                                 orders
                                           where
                                                 disc_amt > '0'  
                                           )
from
       orders
Group by 
       month(invoice_date)

Currently I am getting result as below

month Sales_Amount_Without_Discount Sales_Amount_With_Discount
Jan 50 110
Feb 30 110
Mar 80 110

Thank you

CodePudding user response:

You can do this by putting a case expression within your SUM(), e.g.

SELECT  MONTH(invoice_date),
        Sales_Amount_Without_Discount = SUM(sales_amt),
        Sales_Amount_With_Discount = SUM(CASE WHEN Disc_Amt > 0 THEN sales_amt ELSE 0 END)
FROM    orders
GROUP BY
        MONTH(invoice_date);
  • Related