T
T
timur_gis2020-07-04 15:38:24
PostgreSQL
timur_gis, 2020-07-04 15:38:24

How to group overlapping values ​​in SQL?

There is a table:
table
xy
500 1.0
400 2.3
101 4.1

select 
case when x in (500,400,101) then 'three'
case when x in (500,400) then 'one'
else '' end as "group",
sum (y) as "sum",
from table
group by
"group"

Result:
table
group sum
one 3.3
three 7.4

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
d-stream, 2020-07-04
@d-stream

group by case when x in (500,400,101) then 'three' case when x in (500,400) then 'one' else '' end

R
Ruslan., 2020-07-04
@LaRN

It would be possible to add another table of groups with x and group fields. Join your table with a new table by the x field and group by the group field. In your version, at some point, the case can become very complex and unreadable, and to add a new group, you always need to add a request, and this is not buzzing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question