Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First, we need to find out if the "colors" for two "ids" are the same. The following query does a full outer join on <code>color</code>, and then aggregates by <code>id</code>. If two <code>id</code>s have the same color, then the full outer join always matches -- there are no NULLs:</p> <pre><code>select s1.id, s2.id from s s1 full outer join s s2 on s1.color = s2.color group by s1.id, s2.id having sum(case when s1.color is null then 1 else 0 end) = 0 and sum(case when s2.color is null then 1 else 0 end) = 0 </code></pre> <p>Using the same idea, we can assign the minimum s1.id as the "id" of the group. This group id then gives us the information needed for the final aggregation:</p> <pre><code>select s3.groupid, sum(s3.quantity) as quantity, s3.color as color from (select min(s1.id) as groupid, s2.id from (select s1.id, s2.id from s s1 full outer join s s2 on s1.color = s2.color group by s1.id, s2.id having sum(case when s1.color is null then 1 else 0 end) = 0 and sum(case when s2.color is null then 1 else 0 end) = 0 ) ss group by s2.id ) sg join s s3 on sg.id = s.id group by sg.groupid, s3.color </code></pre> <p>In DB2 you can also do this with <code>listagg</code>. First you need to get the list of colors to identify commonality, and then use it:</p> <pre><code>select min(s.id) as groupid, sum(s.quantity) as quantity, s.color from (select id, listagg(color order by color) as thegroup from s group by id ) sg join s on sg.id = s.id group by sg.thegroup, s.color </code></pre> <p>This is probably more efficient than the first solution.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload