简体   繁体   中英

Using case add different values in sql

There is a table named Product which contains three column- name,id and price . In the below query i want to do something like If id 1,2 and 3 exist then it add id 1.id 2 and id 3's price or if only id 1 and 2 exist then it add only id 1 and id 2's price

select
   name,
   id,

   case 
      when id in(1,2,3) then sum(price) as total
      else ' '
   end
   case
      when id in(4,5,6) then sum (price) as total
      else ' '
   end
from
   Product
group by
   name,
   id;

But its not working properly.

Sample data:

Name ID PRICE
A     1   30
B     2   10
C     5   20

Expected output:

NAME ID TOTAL 
A    1    40
B    2    40
C    5    20

Assuming you have a unique Id, you could try Sum() Over() :

Select Name, Id, 
    Sum(Price) Over (partition by (case when id in (1,2,3) then 1 else id end)) NewPrice
From Table1

Results and Fiddle demo :

| NAME | ID | NEWPRICE |
|------|----|----------|
|    A |  1 |       40 |
|    B |  2 |       40 |
|    C |  5 |       20 |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM