Using Sum of Group Concat in Having clause

noname :

I want to find all ids of which sum of group_concat is 0 . Here is simplified table from mine.

╔════╦════╦══════════════╦
║ id ║ did║ group_concat ║
╠════╬════╬══════════════╬
║  1 ║  1 ║ 1,1,1        ║
║  2 ║  1 ║ 0            ║
║  3 ║  2 ║ 1,-1         ║
║  4 ║  2 ║ 1,-1,0       ║
║  5 ║  2 ║ 0,0,0        ║
║  6 ║  3 ║ 2,-2         ║
║  7 ║  3 ║ 1,-1,0       ║
║  8 ║  3 ║ 0,0,0        ║
╚════╩════╩══════════════╩

I want to get when sum of group_concat is 0 in the same dids. If sum of group concat in any of dids is not equal to zero, it shouldn't be on the table.

Here is the table below for better understanding.

╔═════╦═════════════════════╦
║ did ║ sum of group_concat ║
╠═════╬═════════════════════╬
║  2  ║ 0                   ║
║  3  ║ 0                   ║
╚═════╩═════════════════════╩

And this is the query statement I am trying to use.

select sum(val)
from user
group by did
having sum(val) = 0

seems sum in group_concat is not available.

is there any efficient way?

thank you in advance

GMB :

One solution involves unnesting the csv lists with a table of numbers:

select
    t.did,
    sum(substring_index(substring_index(grp_concat, ',', n.n), ',', - 1)) sum_of_grp_concat
from mytable t
inner join (select 1 n union all select 2 union all select 3 union all select 4 union all select 5) n
    on n.n <= 1 + char_length(grp_concat) - char_length(replace(grp_concat, ',', ''))
group by t.did
having sum_of_grp_concat = 0

The query joins the original table with the derived number table, and extracts each individual value using string functions; all that is left to is aggregate and filter with the having clause.

Demo on DB Fiddle:

did | sum_of_grp_concat
--: | ----------------:
  2 |                 0
  3 |                 0

This task would be far more easier if you were to fix your schema in order to store each csv value in a separate table row. Storing csv lists in a database column is a typical SQL antipattern: on this topic, I would recommend reading this famous SO answer.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=297544&siteId=1