Using FOR XML to Concatenate multiple fields











up vote
0
down vote

favorite












My Data is structured like this:





and I'm trying to use STUFF/FOR XML PATH to concatenate fields.



If I use the examples that I find online I can get the following result:





But I wondered if the following is possible:





I am currently achieving this by calling FOR XML PATH twice, first to concatenate Header3:





and then again to get the desired result.



Is there a way to do it without calling XML PATH twice?










share|improve this question




























    up vote
    0
    down vote

    favorite












    My Data is structured like this:





    and I'm trying to use STUFF/FOR XML PATH to concatenate fields.



    If I use the examples that I find online I can get the following result:





    But I wondered if the following is possible:





    I am currently achieving this by calling FOR XML PATH twice, first to concatenate Header3:





    and then again to get the desired result.



    Is there a way to do it without calling XML PATH twice?










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      My Data is structured like this:





      and I'm trying to use STUFF/FOR XML PATH to concatenate fields.



      If I use the examples that I find online I can get the following result:





      But I wondered if the following is possible:





      I am currently achieving this by calling FOR XML PATH twice, first to concatenate Header3:





      and then again to get the desired result.



      Is there a way to do it without calling XML PATH twice?










      share|improve this question















      My Data is structured like this:





      and I'm trying to use STUFF/FOR XML PATH to concatenate fields.



      If I use the examples that I find online I can get the following result:





      But I wondered if the following is possible:





      I am currently achieving this by calling FOR XML PATH twice, first to concatenate Header3:





      and then again to get the desired result.



      Is there a way to do it without calling XML PATH twice?







      sql sql-server tsql for-xml-path






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 at 18:44









      a_horse_with_no_name

      287k46434529




      287k46434529










      asked Nov 21 at 18:32









      DCulley

      33




      33
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          Are you looking for something like



          CREATE TABLE T(
          Header1 INT,
          Header2 VARCHAR(45),
          Header3 VARCHAR(45)
          );

          INSERT INTO T VALUES
          (123, 'A', 'aaa'),
          (123, 'B', 'bbb'),
          (123, 'C', 'ccc'),
          (123, 'C', 'ddd'),
          (456, 'E', 'eee');

          WITH H3 AS
          (
          SELECT DISTINCT Header1, Header2,
          STUFF(
          (
          SELECT ',' + Header3
          FROM T
          WHERE Header2 = H2.Header2
          FOR XML PATH('')
          ), 1, 1, ''
          ) Res
          FROM T H2
          )

          SELECT DISTINCT
          Header1,
          STUFF(
          (SELECT ' '+ Header2 + ':' + Res + '|'
          FROM H3
          WHERE Header1 = TT.Header1
          FOR XML PATH('')
          ), 1, 1, ''
          ) Desired
          FROM H3 TT;


          Returns:



          +---------+--------------------------+
          | Header1 | Desired |
          +---------+--------------------------+
          | 123 | A:aaa| B:bbb| C:ccc,ddd| |
          | 456 | E:eee| |
          +---------+--------------------------+


          Demo






          share|improve this answer





















          • I am. This is a lot cleaner and clearer than my current query so thank you. But I was hoping to see if it could be done without calling FOR XML twice.
            – DCulley
            Nov 21 at 19:46












          • @DCulley, This structure is a doubled 1:n relation actually (that clearly points to the fact, that this screams for a different table design). However, You need some kind of join or (correlated) sub-query to gather all the related Header2 data and one more step to bind the related Header3 data to their correspoding Header2. This might be solved better in your presentation layer...
            – Shnugo
            Nov 21 at 22:19










          • @Shnugo Ok thank you for the input.
            – DCulley
            Nov 22 at 7:17











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53418489%2fusing-for-xml-to-concatenate-multiple-fields%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote



          accepted










          Are you looking for something like



          CREATE TABLE T(
          Header1 INT,
          Header2 VARCHAR(45),
          Header3 VARCHAR(45)
          );

          INSERT INTO T VALUES
          (123, 'A', 'aaa'),
          (123, 'B', 'bbb'),
          (123, 'C', 'ccc'),
          (123, 'C', 'ddd'),
          (456, 'E', 'eee');

          WITH H3 AS
          (
          SELECT DISTINCT Header1, Header2,
          STUFF(
          (
          SELECT ',' + Header3
          FROM T
          WHERE Header2 = H2.Header2
          FOR XML PATH('')
          ), 1, 1, ''
          ) Res
          FROM T H2
          )

          SELECT DISTINCT
          Header1,
          STUFF(
          (SELECT ' '+ Header2 + ':' + Res + '|'
          FROM H3
          WHERE Header1 = TT.Header1
          FOR XML PATH('')
          ), 1, 1, ''
          ) Desired
          FROM H3 TT;


          Returns:



          +---------+--------------------------+
          | Header1 | Desired |
          +---------+--------------------------+
          | 123 | A:aaa| B:bbb| C:ccc,ddd| |
          | 456 | E:eee| |
          +---------+--------------------------+


          Demo






          share|improve this answer





















          • I am. This is a lot cleaner and clearer than my current query so thank you. But I was hoping to see if it could be done without calling FOR XML twice.
            – DCulley
            Nov 21 at 19:46












          • @DCulley, This structure is a doubled 1:n relation actually (that clearly points to the fact, that this screams for a different table design). However, You need some kind of join or (correlated) sub-query to gather all the related Header2 data and one more step to bind the related Header3 data to their correspoding Header2. This might be solved better in your presentation layer...
            – Shnugo
            Nov 21 at 22:19










          • @Shnugo Ok thank you for the input.
            – DCulley
            Nov 22 at 7:17















          up vote
          0
          down vote



          accepted










          Are you looking for something like



          CREATE TABLE T(
          Header1 INT,
          Header2 VARCHAR(45),
          Header3 VARCHAR(45)
          );

          INSERT INTO T VALUES
          (123, 'A', 'aaa'),
          (123, 'B', 'bbb'),
          (123, 'C', 'ccc'),
          (123, 'C', 'ddd'),
          (456, 'E', 'eee');

          WITH H3 AS
          (
          SELECT DISTINCT Header1, Header2,
          STUFF(
          (
          SELECT ',' + Header3
          FROM T
          WHERE Header2 = H2.Header2
          FOR XML PATH('')
          ), 1, 1, ''
          ) Res
          FROM T H2
          )

          SELECT DISTINCT
          Header1,
          STUFF(
          (SELECT ' '+ Header2 + ':' + Res + '|'
          FROM H3
          WHERE Header1 = TT.Header1
          FOR XML PATH('')
          ), 1, 1, ''
          ) Desired
          FROM H3 TT;


          Returns:



          +---------+--------------------------+
          | Header1 | Desired |
          +---------+--------------------------+
          | 123 | A:aaa| B:bbb| C:ccc,ddd| |
          | 456 | E:eee| |
          +---------+--------------------------+


          Demo






          share|improve this answer





















          • I am. This is a lot cleaner and clearer than my current query so thank you. But I was hoping to see if it could be done without calling FOR XML twice.
            – DCulley
            Nov 21 at 19:46












          • @DCulley, This structure is a doubled 1:n relation actually (that clearly points to the fact, that this screams for a different table design). However, You need some kind of join or (correlated) sub-query to gather all the related Header2 data and one more step to bind the related Header3 data to their correspoding Header2. This might be solved better in your presentation layer...
            – Shnugo
            Nov 21 at 22:19










          • @Shnugo Ok thank you for the input.
            – DCulley
            Nov 22 at 7:17













          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          Are you looking for something like



          CREATE TABLE T(
          Header1 INT,
          Header2 VARCHAR(45),
          Header3 VARCHAR(45)
          );

          INSERT INTO T VALUES
          (123, 'A', 'aaa'),
          (123, 'B', 'bbb'),
          (123, 'C', 'ccc'),
          (123, 'C', 'ddd'),
          (456, 'E', 'eee');

          WITH H3 AS
          (
          SELECT DISTINCT Header1, Header2,
          STUFF(
          (
          SELECT ',' + Header3
          FROM T
          WHERE Header2 = H2.Header2
          FOR XML PATH('')
          ), 1, 1, ''
          ) Res
          FROM T H2
          )

          SELECT DISTINCT
          Header1,
          STUFF(
          (SELECT ' '+ Header2 + ':' + Res + '|'
          FROM H3
          WHERE Header1 = TT.Header1
          FOR XML PATH('')
          ), 1, 1, ''
          ) Desired
          FROM H3 TT;


          Returns:



          +---------+--------------------------+
          | Header1 | Desired |
          +---------+--------------------------+
          | 123 | A:aaa| B:bbb| C:ccc,ddd| |
          | 456 | E:eee| |
          +---------+--------------------------+


          Demo






          share|improve this answer












          Are you looking for something like



          CREATE TABLE T(
          Header1 INT,
          Header2 VARCHAR(45),
          Header3 VARCHAR(45)
          );

          INSERT INTO T VALUES
          (123, 'A', 'aaa'),
          (123, 'B', 'bbb'),
          (123, 'C', 'ccc'),
          (123, 'C', 'ddd'),
          (456, 'E', 'eee');

          WITH H3 AS
          (
          SELECT DISTINCT Header1, Header2,
          STUFF(
          (
          SELECT ',' + Header3
          FROM T
          WHERE Header2 = H2.Header2
          FOR XML PATH('')
          ), 1, 1, ''
          ) Res
          FROM T H2
          )

          SELECT DISTINCT
          Header1,
          STUFF(
          (SELECT ' '+ Header2 + ':' + Res + '|'
          FROM H3
          WHERE Header1 = TT.Header1
          FOR XML PATH('')
          ), 1, 1, ''
          ) Desired
          FROM H3 TT;


          Returns:



          +---------+--------------------------+
          | Header1 | Desired |
          +---------+--------------------------+
          | 123 | A:aaa| B:bbb| C:ccc,ddd| |
          | 456 | E:eee| |
          +---------+--------------------------+


          Demo







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 at 19:39









          Sami

          6,65531038




          6,65531038












          • I am. This is a lot cleaner and clearer than my current query so thank you. But I was hoping to see if it could be done without calling FOR XML twice.
            – DCulley
            Nov 21 at 19:46












          • @DCulley, This structure is a doubled 1:n relation actually (that clearly points to the fact, that this screams for a different table design). However, You need some kind of join or (correlated) sub-query to gather all the related Header2 data and one more step to bind the related Header3 data to their correspoding Header2. This might be solved better in your presentation layer...
            – Shnugo
            Nov 21 at 22:19










          • @Shnugo Ok thank you for the input.
            – DCulley
            Nov 22 at 7:17


















          • I am. This is a lot cleaner and clearer than my current query so thank you. But I was hoping to see if it could be done without calling FOR XML twice.
            – DCulley
            Nov 21 at 19:46












          • @DCulley, This structure is a doubled 1:n relation actually (that clearly points to the fact, that this screams for a different table design). However, You need some kind of join or (correlated) sub-query to gather all the related Header2 data and one more step to bind the related Header3 data to their correspoding Header2. This might be solved better in your presentation layer...
            – Shnugo
            Nov 21 at 22:19










          • @Shnugo Ok thank you for the input.
            – DCulley
            Nov 22 at 7:17
















          I am. This is a lot cleaner and clearer than my current query so thank you. But I was hoping to see if it could be done without calling FOR XML twice.
          – DCulley
          Nov 21 at 19:46






          I am. This is a lot cleaner and clearer than my current query so thank you. But I was hoping to see if it could be done without calling FOR XML twice.
          – DCulley
          Nov 21 at 19:46














          @DCulley, This structure is a doubled 1:n relation actually (that clearly points to the fact, that this screams for a different table design). However, You need some kind of join or (correlated) sub-query to gather all the related Header2 data and one more step to bind the related Header3 data to their correspoding Header2. This might be solved better in your presentation layer...
          – Shnugo
          Nov 21 at 22:19




          @DCulley, This structure is a doubled 1:n relation actually (that clearly points to the fact, that this screams for a different table design). However, You need some kind of join or (correlated) sub-query to gather all the related Header2 data and one more step to bind the related Header3 data to their correspoding Header2. This might be solved better in your presentation layer...
          – Shnugo
          Nov 21 at 22:19












          @Shnugo Ok thank you for the input.
          – DCulley
          Nov 22 at 7:17




          @Shnugo Ok thank you for the input.
          – DCulley
          Nov 22 at 7:17


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53418489%2fusing-for-xml-to-concatenate-multiple-fields%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

          Calculate evaluation metrics using cross_val_predict sklearn

          Insert data from modal to MySQL (multiple modal on website)