DB2 Distinct + xmlagg Query

白昼怎懂夜的黑 提交于 2019-12-01 09:12:16

Came across your question after asking the same one myself. The solution I came up with is to use a common table expression with DISTINCT.

WITH q1 (id, specialization) AS
  (
    SELECT DISTINCT id, specialization
      FROM table_name
  )
SELECT q1.id,
    XMLELEMENT(
      NAME "Specializations",
      XMLAGG(
        XMLELEMENT(NAME "Specialization", q1.specialization)))
  FROM q1
  GROUP BY q1.id

In your case, it would be easier and clearer to use subselects instead (XMLELEMENT boilerplate elided for clarity):

SELECT t.id, XMLAGG(q1.specialization), XMLAGG(q2.basic_skill2),
    XMLAGG(q3.basic_skill1)
  FROM table_name t,
    (SELECT DISTINCT id, specialization FROM table_name) q1,
    (SELECT DISTINCT id, basic_skill2 FROM table_name) q2,
    (SELECT DISTINCT id, basic_skill1 FROM table_name) q3
  WHERE t.id = q1.id AND t.id = q2.id AND t.id = q3.id
  GROUP BY t.id

There may well be an easier way, but this is what I came up with.

Also, you might want to take advantage of functions like XMLQUERY and XSLTRANSFORM. Much simpler and less error-prone than the manual way you're doing it.

The select distinct won't work in case of tables with no duplicates, because of multiple joins giving all the combinations of the values of every join. That leads to duplicates in the aggregate function.

I've found that pushing the group bys and the aggregate functions to subqueries in the from part gives the best results.

SELECT t.id, q1.values, q2.values, q3.values
FROM table_name t,
inner join (select t1.id, listagg(t1.value,',') as values
            from table_name1 t1 inner join table_name t on t.id=t1.id
            group by t1.id) q1 on t.id = q1.id
inner join (select t2.id, listagg(t2.value,',') as values
            from table_name2 t2 inner join table_name t on t.id=t2.id
            group by t2.id) q2 on t.id = q2.id
inner join (select t3.id, listagg(t3.value,',') as values
            from table_name3 t3 inner join table_name t on t.id=t3.id
            group by t3.id) q3 on t.id = q3.id
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!