Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find sum of price having same IDs in IN clause

I have a small query related to calculating the total price having same IDs as twice or multiple times in the IN clause.

Let me explain: I have the following table named data

id  |   price |
===============
1   |   100   |
2   |   150   |
3   |   200   |

I am executing the following query:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT SUM(price) FROM data WHERE id IN (1,2,3,1,2)

It return me 450

But I want to get 700

Please someone help.

>Solution :

What you can do is a a join between a set of the ids you want and your table, then get the sum:

with u as
(select 1 as id
union all select 2
union all select 3
union all select 1
union all select 2)
select sum(price)
from data natural join u

Fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading