How to SUM total with different discount?

Lylyy 380 Reputation points
2023-08-31T06:57:16.13+00:00

I have a table with columns: order_id ,product and price.

I need to query the total of each order_id. And for differnt product, there are different discount.

This is my query:

declare @temp table (order_id int,product varchar(10),price int)
insert into @temp values
(1,'AA',100),(1,'AA',87),(1,'BB',56),(1,'BB',82),
(2,'AA',167),(2,'AA',43),(2,'BB',23),(2,'BB',78)

select order_id,
       case when product='AA' then SUM(price)*0.90
            when product='BB' then SUM(price)*0.85 end as total
from @temp
group by order_id,product

However, I only want one row for each order_id in the final result. How to rewrite this query?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,494 questions
0 comments No comments
{count} votes

Accepted answer
  1. LiHongMSFT-4306 31,471 Reputation points
    2023-08-31T07:02:50.0533333+00:00

    Hi @Lylyy

    Check this query:

    select order_id
          ,SUM(case when product='AA' then price*0.90
                    when product='BB' then price*0.85 end) as total
    from @temp
    

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    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.