XML : PostgreSQL Xpath to select element and it's child attribute as two columns

I have a table history (id int, content xml) in postgreSQL. XML content for one of the id as as following

  <history-data>        <history recorded-date="20110601">          <assignees>            <assignee>               <last-name>CIENA LUXEMBOURG</last-name>            </assignee>          </assignees>          <assignors>            <assignor execution-date="20110517">                <last-name>NORTEL NETWORKS LIMITED</last-name>            </assignor>          </assignors>        </history>        <history recorded-date="20110601">          <assignees>            <assignee>                <last-name>CIENA CORPORATION</last-name>            </assignee>          </assignees>          <assignors>            <assignor execution-date="20110527">                <last-name>CIENA LUXEMBOURG</last-name>            </assignor>          </assignors>        </history>        <history recorded-date="20090430">          <assignees>            <assignee>               <last-name>NORTEL NETWORKS</last-name>             </assignee>          </assignees>          <assignors>            <assignor execution-date="20090424">                <last-name>MAK, GARY</last-name>            </assignor>            <assignor execution-date="20090424">                <last-name>VELEZ, EDGAR</last-name>            </assignor>          </assignors>        </history>      </history-data>    

Here, i want to get last-name & it's respective execution-date. For the above example, i want the following output

  last-name                   execution-date  ================            ==============  CIENA LUXEMBOURG              20110517  CIENA CORPORATION             20110527  NORTEL NETWORKS               20090424    

I am able to generate all possible combinations using the following SQL query but not able to get output like above

  SELECT id, unnest(CAST(xpath('/history-data/history/assignees/assignee/last-name/text()',content) AS text)::text[]) AS last-name,  unnest(CAST(xpath('/history-data/history/assignors/assignor/@execution-date',content) AS text)::text[]) AS execution-date  FROM history  WHERE id = 10    

any suggestions on how can this be done ?

No comments:

Post a Comment