Extracting multiple rows from a table with two linked tables in SQL Server












0















I have a table, let's call it Case the case table contains basic information about a case, such as the CaseNumber and the CaseOwner.



In a second table CasePersons, details about individuals attached to a particular case number are held. This includes PersonId, FirstName and LastName. CasePersons links to Case through CaseNumber.



In a third table, ContactDetails a number of phone numbers associated with a particular person are stored. The Type column within ContactDetails represents the type of phone number e.g. Home, mobile or work. ContactDetails links to CasePersons through PersonId



More clearly:



Case
------------------------
CaseNumber CaseOwner
1 Owner1
2 Owner2
3 Owner3

CasePersons
---------------------
PersonId CaseNumber FirstName LastName
1 1 Bob Person
2 1 Jim Human
3 2 Gary Man
4 3 Pete Smith
5 3 Matt Jones


CaseDetails
-------------------------
PersonId Detail Type
1 0123456789 1
1 1111111111 2
2 2222222222 1
1 0101001011 3
2 1234123412 2
3 0000011111 1
3 1231231231 2


I want to be able to write a query that can pull back the basic details of a case, as well as all of the individuals associated with a case and ALL of the associated phone numbers.



How exactly would I construct a query to extract this information? I can't seem to find the information on this on Google as I'm not sure what to search for.



The whole point of this is so that I can find all of the associated numbers for a particular case and store them in one location.



Expected output



CaseNumber    CaseOwner    Person1FirstName     Person1LastName     Person1HomeNumber    Person1MobileNumber     Person1WorkNumber     Person2FirstName     Person2LastName     Person2HomeNumber    Person2MobileNumber     Person2WorkNumber  
1 Owner1 Bob Person 0123456789 1111111111 0101001011 Jim Human 2222222222 1234123412









share|improve this question




















  • 1





    add your expected output in table format

    – fa06
    Nov 19 '18 at 13:35











  • @fa06 Added the expected output to the OP

    – Jake12342134
    Nov 19 '18 at 14:02











  • As far as having dedicated columns for person1, person2, etc. You don't. That's an extremely non-sql way of looking at things. By all means transpose the data when presenting it in a GUI or something, but you do that application side, not database side. In terms of data processing, in terms of SQL and relational databases, stick to the normalised structure (one person per row, so you can have as many people as you like without having to change the structure or the query).

    – MatBailie
    Nov 19 '18 at 15:26













  • @MatBailie What should I do if the database I'm extracting this data from has two people associated with a particular case in a single row? There will only ever be a maximum of two people associated with a case, but the details of these two people are stored within the same row. Should I separate the data within SQL or do this later on out of the database?

    – Jake12342134
    Nov 19 '18 at 15:55


















0















I have a table, let's call it Case the case table contains basic information about a case, such as the CaseNumber and the CaseOwner.



In a second table CasePersons, details about individuals attached to a particular case number are held. This includes PersonId, FirstName and LastName. CasePersons links to Case through CaseNumber.



In a third table, ContactDetails a number of phone numbers associated with a particular person are stored. The Type column within ContactDetails represents the type of phone number e.g. Home, mobile or work. ContactDetails links to CasePersons through PersonId



More clearly:



Case
------------------------
CaseNumber CaseOwner
1 Owner1
2 Owner2
3 Owner3

CasePersons
---------------------
PersonId CaseNumber FirstName LastName
1 1 Bob Person
2 1 Jim Human
3 2 Gary Man
4 3 Pete Smith
5 3 Matt Jones


CaseDetails
-------------------------
PersonId Detail Type
1 0123456789 1
1 1111111111 2
2 2222222222 1
1 0101001011 3
2 1234123412 2
3 0000011111 1
3 1231231231 2


I want to be able to write a query that can pull back the basic details of a case, as well as all of the individuals associated with a case and ALL of the associated phone numbers.



How exactly would I construct a query to extract this information? I can't seem to find the information on this on Google as I'm not sure what to search for.



The whole point of this is so that I can find all of the associated numbers for a particular case and store them in one location.



Expected output



CaseNumber    CaseOwner    Person1FirstName     Person1LastName     Person1HomeNumber    Person1MobileNumber     Person1WorkNumber     Person2FirstName     Person2LastName     Person2HomeNumber    Person2MobileNumber     Person2WorkNumber  
1 Owner1 Bob Person 0123456789 1111111111 0101001011 Jim Human 2222222222 1234123412









share|improve this question




















  • 1





    add your expected output in table format

    – fa06
    Nov 19 '18 at 13:35











  • @fa06 Added the expected output to the OP

    – Jake12342134
    Nov 19 '18 at 14:02











  • As far as having dedicated columns for person1, person2, etc. You don't. That's an extremely non-sql way of looking at things. By all means transpose the data when presenting it in a GUI or something, but you do that application side, not database side. In terms of data processing, in terms of SQL and relational databases, stick to the normalised structure (one person per row, so you can have as many people as you like without having to change the structure or the query).

    – MatBailie
    Nov 19 '18 at 15:26













  • @MatBailie What should I do if the database I'm extracting this data from has two people associated with a particular case in a single row? There will only ever be a maximum of two people associated with a case, but the details of these two people are stored within the same row. Should I separate the data within SQL or do this later on out of the database?

    – Jake12342134
    Nov 19 '18 at 15:55
















0












0








0








I have a table, let's call it Case the case table contains basic information about a case, such as the CaseNumber and the CaseOwner.



In a second table CasePersons, details about individuals attached to a particular case number are held. This includes PersonId, FirstName and LastName. CasePersons links to Case through CaseNumber.



In a third table, ContactDetails a number of phone numbers associated with a particular person are stored. The Type column within ContactDetails represents the type of phone number e.g. Home, mobile or work. ContactDetails links to CasePersons through PersonId



More clearly:



Case
------------------------
CaseNumber CaseOwner
1 Owner1
2 Owner2
3 Owner3

CasePersons
---------------------
PersonId CaseNumber FirstName LastName
1 1 Bob Person
2 1 Jim Human
3 2 Gary Man
4 3 Pete Smith
5 3 Matt Jones


CaseDetails
-------------------------
PersonId Detail Type
1 0123456789 1
1 1111111111 2
2 2222222222 1
1 0101001011 3
2 1234123412 2
3 0000011111 1
3 1231231231 2


I want to be able to write a query that can pull back the basic details of a case, as well as all of the individuals associated with a case and ALL of the associated phone numbers.



How exactly would I construct a query to extract this information? I can't seem to find the information on this on Google as I'm not sure what to search for.



The whole point of this is so that I can find all of the associated numbers for a particular case and store them in one location.



Expected output



CaseNumber    CaseOwner    Person1FirstName     Person1LastName     Person1HomeNumber    Person1MobileNumber     Person1WorkNumber     Person2FirstName     Person2LastName     Person2HomeNumber    Person2MobileNumber     Person2WorkNumber  
1 Owner1 Bob Person 0123456789 1111111111 0101001011 Jim Human 2222222222 1234123412









share|improve this question
















I have a table, let's call it Case the case table contains basic information about a case, such as the CaseNumber and the CaseOwner.



In a second table CasePersons, details about individuals attached to a particular case number are held. This includes PersonId, FirstName and LastName. CasePersons links to Case through CaseNumber.



In a third table, ContactDetails a number of phone numbers associated with a particular person are stored. The Type column within ContactDetails represents the type of phone number e.g. Home, mobile or work. ContactDetails links to CasePersons through PersonId



More clearly:



Case
------------------------
CaseNumber CaseOwner
1 Owner1
2 Owner2
3 Owner3

CasePersons
---------------------
PersonId CaseNumber FirstName LastName
1 1 Bob Person
2 1 Jim Human
3 2 Gary Man
4 3 Pete Smith
5 3 Matt Jones


CaseDetails
-------------------------
PersonId Detail Type
1 0123456789 1
1 1111111111 2
2 2222222222 1
1 0101001011 3
2 1234123412 2
3 0000011111 1
3 1231231231 2


I want to be able to write a query that can pull back the basic details of a case, as well as all of the individuals associated with a case and ALL of the associated phone numbers.



How exactly would I construct a query to extract this information? I can't seem to find the information on this on Google as I'm not sure what to search for.



The whole point of this is so that I can find all of the associated numbers for a particular case and store them in one location.



Expected output



CaseNumber    CaseOwner    Person1FirstName     Person1LastName     Person1HomeNumber    Person1MobileNumber     Person1WorkNumber     Person2FirstName     Person2LastName     Person2HomeNumber    Person2MobileNumber     Person2WorkNumber  
1 Owner1 Bob Person 0123456789 1111111111 0101001011 Jim Human 2222222222 1234123412






sql sql-server






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 '18 at 14:02







Jake12342134

















asked Nov 19 '18 at 13:33









Jake12342134Jake12342134

1108




1108








  • 1





    add your expected output in table format

    – fa06
    Nov 19 '18 at 13:35











  • @fa06 Added the expected output to the OP

    – Jake12342134
    Nov 19 '18 at 14:02











  • As far as having dedicated columns for person1, person2, etc. You don't. That's an extremely non-sql way of looking at things. By all means transpose the data when presenting it in a GUI or something, but you do that application side, not database side. In terms of data processing, in terms of SQL and relational databases, stick to the normalised structure (one person per row, so you can have as many people as you like without having to change the structure or the query).

    – MatBailie
    Nov 19 '18 at 15:26













  • @MatBailie What should I do if the database I'm extracting this data from has two people associated with a particular case in a single row? There will only ever be a maximum of two people associated with a case, but the details of these two people are stored within the same row. Should I separate the data within SQL or do this later on out of the database?

    – Jake12342134
    Nov 19 '18 at 15:55
















  • 1





    add your expected output in table format

    – fa06
    Nov 19 '18 at 13:35











  • @fa06 Added the expected output to the OP

    – Jake12342134
    Nov 19 '18 at 14:02











  • As far as having dedicated columns for person1, person2, etc. You don't. That's an extremely non-sql way of looking at things. By all means transpose the data when presenting it in a GUI or something, but you do that application side, not database side. In terms of data processing, in terms of SQL and relational databases, stick to the normalised structure (one person per row, so you can have as many people as you like without having to change the structure or the query).

    – MatBailie
    Nov 19 '18 at 15:26













  • @MatBailie What should I do if the database I'm extracting this data from has two people associated with a particular case in a single row? There will only ever be a maximum of two people associated with a case, but the details of these two people are stored within the same row. Should I separate the data within SQL or do this later on out of the database?

    – Jake12342134
    Nov 19 '18 at 15:55










1




1





add your expected output in table format

– fa06
Nov 19 '18 at 13:35





add your expected output in table format

– fa06
Nov 19 '18 at 13:35













@fa06 Added the expected output to the OP

– Jake12342134
Nov 19 '18 at 14:02





@fa06 Added the expected output to the OP

– Jake12342134
Nov 19 '18 at 14:02













As far as having dedicated columns for person1, person2, etc. You don't. That's an extremely non-sql way of looking at things. By all means transpose the data when presenting it in a GUI or something, but you do that application side, not database side. In terms of data processing, in terms of SQL and relational databases, stick to the normalised structure (one person per row, so you can have as many people as you like without having to change the structure or the query).

– MatBailie
Nov 19 '18 at 15:26







As far as having dedicated columns for person1, person2, etc. You don't. That's an extremely non-sql way of looking at things. By all means transpose the data when presenting it in a GUI or something, but you do that application side, not database side. In terms of data processing, in terms of SQL and relational databases, stick to the normalised structure (one person per row, so you can have as many people as you like without having to change the structure or the query).

– MatBailie
Nov 19 '18 at 15:26















@MatBailie What should I do if the database I'm extracting this data from has two people associated with a particular case in a single row? There will only ever be a maximum of two people associated with a case, but the details of these two people are stored within the same row. Should I separate the data within SQL or do this later on out of the database?

– Jake12342134
Nov 19 '18 at 15:55







@MatBailie What should I do if the database I'm extracting this data from has two people associated with a particular case in a single row? There will only ever be a maximum of two people associated with a case, but the details of these two people are stored within the same row. Should I separate the data within SQL or do this later on out of the database?

– Jake12342134
Nov 19 '18 at 15:55














3 Answers
3






active

oldest

votes


















0














If you're okay with all the information for one case showing up in multiple rows, you can use multiple joins and an order by to place related rows together.



select
Case.CaseNumber
,CaseOwner
,CasePersons.PersonID
,FirstName
,LastName
,Detail
,Type
from
Case
join CasePersons
on Case.CaseNumber=CasePersons.Casenumber
join CaseDetails
on CasePersons.PersonID=CaseDetails.PersonID
Order by
Case.CaseNumber
,CasePersons.PersonID





share|improve this answer































    0














    Just joining on the respective columns of the tables would do.



    Eg:
    Step 1:You get all of the case information from "Case" table so this would be your driving table.
    Step 2: To get all the persons involved in your case, join with the "CasePersons" table
    case.CaseNumber=casepersons.CaseNumber
    Step 3: Now you got all persons associated with a case as the result of step 2. After this you are interested in extracting the phone numbers of the persons who are involved in your case,so join
    casepersons.personid=casedetails.personid



    Query



     select case.CaseNumber
    ,case.CaseOwner
    ,casepersons.personid
    ,casepersons.firstname
    ,casepersons.lastname
    ,casedetails.Detail
    ,casedetails.Type
    ,case when casedetails.Type=1 then 'Home'
    when casedetails.Type=2 then 'Mobile'
    when casedetails.Type=3 then 'Work'
    end as phone_type
    from case
    join casepersons
    on case.CaseNumber=casepersons.CaseNumber
    join (select personid
    ,max(case when casedetails.Type=1 then details end) as Home_number
    ,max(case when casedetails.Type=2 then details end) as Work_number
    ,max(case when casedetails.Type=3 then details end) as Mobile_number
    from casedetails
    group by personid) as cd_1
    on casepersons.personid=cd_1.personid





    share|improve this answer


























    • So this is close to what I want, except I'd like the Home, Mobile and Work values held in detail to go into three separate columns depending on the value of type. So if type == 1 then the Home Number field is populated, type == 2 then the Mobile Number field is populated etc, how do I do this?

      – Jake12342134
      Nov 19 '18 at 14:18











    • I have tried using three separate cases to populate the fields, but this seems to produce three rows and only populates one of the three fields, not all three.

      – Jake12342134
      Nov 19 '18 at 14:24













    • Modified the query to show up the phone numbers aggregated by personid

      – George Joseph
      Nov 19 '18 at 14:39



















    0














    you can check the following script. I have added dynamic table which is related with maximum person added to the CasePersons table for each case.



    /*
    DROP TABLE #Case;
    DROP TABLE #CasePersons;
    DROP TABLE #CaseDetails;
    DROP TABLE #CaseTemp;
    */
    CREATE TABLE #Case
    (
    CaseNumber INT
    ,CaseOwner VARCHAR(100)
    );

    INSERT INTO #Case VALUES(1,'Owner1'),(2,'Owner2'),(3,'Owner3');

    CREATE TABLE #CasePersons
    (
    PersonId INT
    ,CaseNumber INT
    ,FirstName VARCHAR(100)
    ,LastName VARCHAR(100)
    );

    INSERT INTO #CasePersons
    VALUES(1,1,'Bob','Person'),(2,1,'Jim','Human'),(3,2,'Gary','Man'),(4,3,'Pete','Smith'),(5,3,'Matt','Jones');

    CREATE TABLE #CaseDetails
    (
    PersonId INT
    ,Detail VARCHAR(100)
    ,[TYPE] INT
    );

    INSERT INTO #CaseDetails
    VALUES
    (1,'0123456789',1)
    ,(1,'1111111111',2)
    ,(2,'2222222222',1)
    ,(1,'0101001011',3)
    ,(2,'1234123412',2)
    ,(3,'0000011111',1)
    ,(3,'1231231231',2);



    SELECT c.CaseNumber
    ,c.CaseOwner
    ,ROW_NUMBER() OVER (PARTITION BY C.CaseNumber ORDER BY CD.PersonId) RowNumber
    ,CP.PersonId
    ,CP.FirstName
    ,CP.LastName
    ,CD.HomeNumber
    ,CD.MobileNumber
    ,CD.WorkNumber
    INTO #CaseTemp
    FROM #Case C
    LEFT JOIN #CasePersons CP ON C.CaseNumber = CP.CaseNumber
    LEFT JOIN
    (
    SELECT PersonId
    ,MAX(CASE WHEN TYPE=1 THEN Detail END) HomeNumber
    ,MAX(CASE WHEN TYPE=2 THEN Detail END) MobileNumber
    ,MAX(CASE WHEN TYPE=3 THEN Detail END) WorkNumber
    FROM #CaseDetails
    GROUP BY PersonId
    ) CD ON CP.PersonId = CD.PersonId
    --WHERE CD.TYPE=1
    ORDER BY C.CaseNumber
    ,CP.PersonId

    --Create result table
    DROP TABLE #CaseList
    GO
    CREATE TABLE #CaseList
    (
    CaseNumber INT
    ,CaseOwner VARCHAR(100)
    ,Person1FirstName VARCHAR(100)
    ,Person1LastName VARCHAR(100)
    ,Person1HomeNumber VARCHAR(100)
    ,Person1MobileNumber VARCHAR(100)
    ,Person1WorkNumber VARCHAR(100)
    )

    --Insert first person details to the table
    INSERT INTO #CaseList
    SELECT CaseNumber
    ,CaseOwner
    ,FirstName
    ,LastName
    ,HomeNumber
    ,MobileNumber
    ,WorkNumber
    FROM #CaseTemp
    WHERE RowNumber=1

    --Create additional person fields
    DECLARE @SQLString VARCHAR(MAX)=''
    DECLARE @MaxPerson INT=(SELECT MAX(RowNumber) FROM #CaseTemp)
    DECLARE @Seq int=2

    --
    WHILE @MaxPerson>=@Seq
    BEGIN
    SET @SQLString='ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'FirstName VARCHAR(100);'
    SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'LastName VARCHAR(100);'
    SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'HomeNumber VARCHAR(100);'
    SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'MobileNumber VARCHAR(100);'
    SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'WorkNumber VARCHAR(100);'
    SET @Seq +=1
    END

    EXEC (@SQLString)

    --Update additional person details
    SET @SQLString=''

    SET @Seq=2
    WHILE @MaxPerson>=@Seq
    BEGIN
    SET @SQLString=@SQLString+CHAR(13)+'UPDATE #CaseList SET Person'+CAST(@Seq AS VARCHAR)+'FirstName =CT.FirstName
    ,Person'+CAST(@Seq AS VARCHAR)+'LastName =CT.LastName
    ,Person'+CAST(@Seq AS VARCHAR)+'HomeNumber =CT.HomeNumber
    ,Person'+CAST(@Seq AS VARCHAR)+'MobileNumber=CT.MobileNumber
    ,Person'+CAST(@Seq AS VARCHAR)+'WorkNumber =CT.WorkNumber
    FROM #CaseTemp CT
    WHERE #CaseList.CaseNumber=CT.CaseNumber AND CT.RowNumber='+CAST(@Seq AS VARCHAR)+''
    SET @Seq +=1
    END

    EXEC (@SQLString)

    --SELECT * FROM #CaseTemp
    SELECT * FROM #CaseList





    share|improve this answer























      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',
      autoActivateHeartbeat: false,
      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%2f53375775%2fextracting-multiple-rows-from-a-table-with-two-linked-tables-in-sql-server%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      If you're okay with all the information for one case showing up in multiple rows, you can use multiple joins and an order by to place related rows together.



      select
      Case.CaseNumber
      ,CaseOwner
      ,CasePersons.PersonID
      ,FirstName
      ,LastName
      ,Detail
      ,Type
      from
      Case
      join CasePersons
      on Case.CaseNumber=CasePersons.Casenumber
      join CaseDetails
      on CasePersons.PersonID=CaseDetails.PersonID
      Order by
      Case.CaseNumber
      ,CasePersons.PersonID





      share|improve this answer




























        0














        If you're okay with all the information for one case showing up in multiple rows, you can use multiple joins and an order by to place related rows together.



        select
        Case.CaseNumber
        ,CaseOwner
        ,CasePersons.PersonID
        ,FirstName
        ,LastName
        ,Detail
        ,Type
        from
        Case
        join CasePersons
        on Case.CaseNumber=CasePersons.Casenumber
        join CaseDetails
        on CasePersons.PersonID=CaseDetails.PersonID
        Order by
        Case.CaseNumber
        ,CasePersons.PersonID





        share|improve this answer


























          0












          0








          0







          If you're okay with all the information for one case showing up in multiple rows, you can use multiple joins and an order by to place related rows together.



          select
          Case.CaseNumber
          ,CaseOwner
          ,CasePersons.PersonID
          ,FirstName
          ,LastName
          ,Detail
          ,Type
          from
          Case
          join CasePersons
          on Case.CaseNumber=CasePersons.Casenumber
          join CaseDetails
          on CasePersons.PersonID=CaseDetails.PersonID
          Order by
          Case.CaseNumber
          ,CasePersons.PersonID





          share|improve this answer













          If you're okay with all the information for one case showing up in multiple rows, you can use multiple joins and an order by to place related rows together.



          select
          Case.CaseNumber
          ,CaseOwner
          ,CasePersons.PersonID
          ,FirstName
          ,LastName
          ,Detail
          ,Type
          from
          Case
          join CasePersons
          on Case.CaseNumber=CasePersons.Casenumber
          join CaseDetails
          on CasePersons.PersonID=CaseDetails.PersonID
          Order by
          Case.CaseNumber
          ,CasePersons.PersonID






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 19 '18 at 14:02









          Golden RatioGolden Ratio

          137114




          137114

























              0














              Just joining on the respective columns of the tables would do.



              Eg:
              Step 1:You get all of the case information from "Case" table so this would be your driving table.
              Step 2: To get all the persons involved in your case, join with the "CasePersons" table
              case.CaseNumber=casepersons.CaseNumber
              Step 3: Now you got all persons associated with a case as the result of step 2. After this you are interested in extracting the phone numbers of the persons who are involved in your case,so join
              casepersons.personid=casedetails.personid



              Query



               select case.CaseNumber
              ,case.CaseOwner
              ,casepersons.personid
              ,casepersons.firstname
              ,casepersons.lastname
              ,casedetails.Detail
              ,casedetails.Type
              ,case when casedetails.Type=1 then 'Home'
              when casedetails.Type=2 then 'Mobile'
              when casedetails.Type=3 then 'Work'
              end as phone_type
              from case
              join casepersons
              on case.CaseNumber=casepersons.CaseNumber
              join (select personid
              ,max(case when casedetails.Type=1 then details end) as Home_number
              ,max(case when casedetails.Type=2 then details end) as Work_number
              ,max(case when casedetails.Type=3 then details end) as Mobile_number
              from casedetails
              group by personid) as cd_1
              on casepersons.personid=cd_1.personid





              share|improve this answer


























              • So this is close to what I want, except I'd like the Home, Mobile and Work values held in detail to go into three separate columns depending on the value of type. So if type == 1 then the Home Number field is populated, type == 2 then the Mobile Number field is populated etc, how do I do this?

                – Jake12342134
                Nov 19 '18 at 14:18











              • I have tried using three separate cases to populate the fields, but this seems to produce three rows and only populates one of the three fields, not all three.

                – Jake12342134
                Nov 19 '18 at 14:24













              • Modified the query to show up the phone numbers aggregated by personid

                – George Joseph
                Nov 19 '18 at 14:39
















              0














              Just joining on the respective columns of the tables would do.



              Eg:
              Step 1:You get all of the case information from "Case" table so this would be your driving table.
              Step 2: To get all the persons involved in your case, join with the "CasePersons" table
              case.CaseNumber=casepersons.CaseNumber
              Step 3: Now you got all persons associated with a case as the result of step 2. After this you are interested in extracting the phone numbers of the persons who are involved in your case,so join
              casepersons.personid=casedetails.personid



              Query



               select case.CaseNumber
              ,case.CaseOwner
              ,casepersons.personid
              ,casepersons.firstname
              ,casepersons.lastname
              ,casedetails.Detail
              ,casedetails.Type
              ,case when casedetails.Type=1 then 'Home'
              when casedetails.Type=2 then 'Mobile'
              when casedetails.Type=3 then 'Work'
              end as phone_type
              from case
              join casepersons
              on case.CaseNumber=casepersons.CaseNumber
              join (select personid
              ,max(case when casedetails.Type=1 then details end) as Home_number
              ,max(case when casedetails.Type=2 then details end) as Work_number
              ,max(case when casedetails.Type=3 then details end) as Mobile_number
              from casedetails
              group by personid) as cd_1
              on casepersons.personid=cd_1.personid





              share|improve this answer


























              • So this is close to what I want, except I'd like the Home, Mobile and Work values held in detail to go into three separate columns depending on the value of type. So if type == 1 then the Home Number field is populated, type == 2 then the Mobile Number field is populated etc, how do I do this?

                – Jake12342134
                Nov 19 '18 at 14:18











              • I have tried using three separate cases to populate the fields, but this seems to produce three rows and only populates one of the three fields, not all three.

                – Jake12342134
                Nov 19 '18 at 14:24













              • Modified the query to show up the phone numbers aggregated by personid

                – George Joseph
                Nov 19 '18 at 14:39














              0












              0








              0







              Just joining on the respective columns of the tables would do.



              Eg:
              Step 1:You get all of the case information from "Case" table so this would be your driving table.
              Step 2: To get all the persons involved in your case, join with the "CasePersons" table
              case.CaseNumber=casepersons.CaseNumber
              Step 3: Now you got all persons associated with a case as the result of step 2. After this you are interested in extracting the phone numbers of the persons who are involved in your case,so join
              casepersons.personid=casedetails.personid



              Query



               select case.CaseNumber
              ,case.CaseOwner
              ,casepersons.personid
              ,casepersons.firstname
              ,casepersons.lastname
              ,casedetails.Detail
              ,casedetails.Type
              ,case when casedetails.Type=1 then 'Home'
              when casedetails.Type=2 then 'Mobile'
              when casedetails.Type=3 then 'Work'
              end as phone_type
              from case
              join casepersons
              on case.CaseNumber=casepersons.CaseNumber
              join (select personid
              ,max(case when casedetails.Type=1 then details end) as Home_number
              ,max(case when casedetails.Type=2 then details end) as Work_number
              ,max(case when casedetails.Type=3 then details end) as Mobile_number
              from casedetails
              group by personid) as cd_1
              on casepersons.personid=cd_1.personid





              share|improve this answer















              Just joining on the respective columns of the tables would do.



              Eg:
              Step 1:You get all of the case information from "Case" table so this would be your driving table.
              Step 2: To get all the persons involved in your case, join with the "CasePersons" table
              case.CaseNumber=casepersons.CaseNumber
              Step 3: Now you got all persons associated with a case as the result of step 2. After this you are interested in extracting the phone numbers of the persons who are involved in your case,so join
              casepersons.personid=casedetails.personid



              Query



               select case.CaseNumber
              ,case.CaseOwner
              ,casepersons.personid
              ,casepersons.firstname
              ,casepersons.lastname
              ,casedetails.Detail
              ,casedetails.Type
              ,case when casedetails.Type=1 then 'Home'
              when casedetails.Type=2 then 'Mobile'
              when casedetails.Type=3 then 'Work'
              end as phone_type
              from case
              join casepersons
              on case.CaseNumber=casepersons.CaseNumber
              join (select personid
              ,max(case when casedetails.Type=1 then details end) as Home_number
              ,max(case when casedetails.Type=2 then details end) as Work_number
              ,max(case when casedetails.Type=3 then details end) as Mobile_number
              from casedetails
              group by personid) as cd_1
              on casepersons.personid=cd_1.personid






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 19 '18 at 14:39

























              answered Nov 19 '18 at 14:04









              George JosephGeorge Joseph

              1,46559




              1,46559













              • So this is close to what I want, except I'd like the Home, Mobile and Work values held in detail to go into three separate columns depending on the value of type. So if type == 1 then the Home Number field is populated, type == 2 then the Mobile Number field is populated etc, how do I do this?

                – Jake12342134
                Nov 19 '18 at 14:18











              • I have tried using three separate cases to populate the fields, but this seems to produce three rows and only populates one of the three fields, not all three.

                – Jake12342134
                Nov 19 '18 at 14:24













              • Modified the query to show up the phone numbers aggregated by personid

                – George Joseph
                Nov 19 '18 at 14:39



















              • So this is close to what I want, except I'd like the Home, Mobile and Work values held in detail to go into three separate columns depending on the value of type. So if type == 1 then the Home Number field is populated, type == 2 then the Mobile Number field is populated etc, how do I do this?

                – Jake12342134
                Nov 19 '18 at 14:18











              • I have tried using three separate cases to populate the fields, but this seems to produce three rows and only populates one of the three fields, not all three.

                – Jake12342134
                Nov 19 '18 at 14:24













              • Modified the query to show up the phone numbers aggregated by personid

                – George Joseph
                Nov 19 '18 at 14:39

















              So this is close to what I want, except I'd like the Home, Mobile and Work values held in detail to go into three separate columns depending on the value of type. So if type == 1 then the Home Number field is populated, type == 2 then the Mobile Number field is populated etc, how do I do this?

              – Jake12342134
              Nov 19 '18 at 14:18





              So this is close to what I want, except I'd like the Home, Mobile and Work values held in detail to go into three separate columns depending on the value of type. So if type == 1 then the Home Number field is populated, type == 2 then the Mobile Number field is populated etc, how do I do this?

              – Jake12342134
              Nov 19 '18 at 14:18













              I have tried using three separate cases to populate the fields, but this seems to produce three rows and only populates one of the three fields, not all three.

              – Jake12342134
              Nov 19 '18 at 14:24







              I have tried using three separate cases to populate the fields, but this seems to produce three rows and only populates one of the three fields, not all three.

              – Jake12342134
              Nov 19 '18 at 14:24















              Modified the query to show up the phone numbers aggregated by personid

              – George Joseph
              Nov 19 '18 at 14:39





              Modified the query to show up the phone numbers aggregated by personid

              – George Joseph
              Nov 19 '18 at 14:39











              0














              you can check the following script. I have added dynamic table which is related with maximum person added to the CasePersons table for each case.



              /*
              DROP TABLE #Case;
              DROP TABLE #CasePersons;
              DROP TABLE #CaseDetails;
              DROP TABLE #CaseTemp;
              */
              CREATE TABLE #Case
              (
              CaseNumber INT
              ,CaseOwner VARCHAR(100)
              );

              INSERT INTO #Case VALUES(1,'Owner1'),(2,'Owner2'),(3,'Owner3');

              CREATE TABLE #CasePersons
              (
              PersonId INT
              ,CaseNumber INT
              ,FirstName VARCHAR(100)
              ,LastName VARCHAR(100)
              );

              INSERT INTO #CasePersons
              VALUES(1,1,'Bob','Person'),(2,1,'Jim','Human'),(3,2,'Gary','Man'),(4,3,'Pete','Smith'),(5,3,'Matt','Jones');

              CREATE TABLE #CaseDetails
              (
              PersonId INT
              ,Detail VARCHAR(100)
              ,[TYPE] INT
              );

              INSERT INTO #CaseDetails
              VALUES
              (1,'0123456789',1)
              ,(1,'1111111111',2)
              ,(2,'2222222222',1)
              ,(1,'0101001011',3)
              ,(2,'1234123412',2)
              ,(3,'0000011111',1)
              ,(3,'1231231231',2);



              SELECT c.CaseNumber
              ,c.CaseOwner
              ,ROW_NUMBER() OVER (PARTITION BY C.CaseNumber ORDER BY CD.PersonId) RowNumber
              ,CP.PersonId
              ,CP.FirstName
              ,CP.LastName
              ,CD.HomeNumber
              ,CD.MobileNumber
              ,CD.WorkNumber
              INTO #CaseTemp
              FROM #Case C
              LEFT JOIN #CasePersons CP ON C.CaseNumber = CP.CaseNumber
              LEFT JOIN
              (
              SELECT PersonId
              ,MAX(CASE WHEN TYPE=1 THEN Detail END) HomeNumber
              ,MAX(CASE WHEN TYPE=2 THEN Detail END) MobileNumber
              ,MAX(CASE WHEN TYPE=3 THEN Detail END) WorkNumber
              FROM #CaseDetails
              GROUP BY PersonId
              ) CD ON CP.PersonId = CD.PersonId
              --WHERE CD.TYPE=1
              ORDER BY C.CaseNumber
              ,CP.PersonId

              --Create result table
              DROP TABLE #CaseList
              GO
              CREATE TABLE #CaseList
              (
              CaseNumber INT
              ,CaseOwner VARCHAR(100)
              ,Person1FirstName VARCHAR(100)
              ,Person1LastName VARCHAR(100)
              ,Person1HomeNumber VARCHAR(100)
              ,Person1MobileNumber VARCHAR(100)
              ,Person1WorkNumber VARCHAR(100)
              )

              --Insert first person details to the table
              INSERT INTO #CaseList
              SELECT CaseNumber
              ,CaseOwner
              ,FirstName
              ,LastName
              ,HomeNumber
              ,MobileNumber
              ,WorkNumber
              FROM #CaseTemp
              WHERE RowNumber=1

              --Create additional person fields
              DECLARE @SQLString VARCHAR(MAX)=''
              DECLARE @MaxPerson INT=(SELECT MAX(RowNumber) FROM #CaseTemp)
              DECLARE @Seq int=2

              --
              WHILE @MaxPerson>=@Seq
              BEGIN
              SET @SQLString='ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'FirstName VARCHAR(100);'
              SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'LastName VARCHAR(100);'
              SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'HomeNumber VARCHAR(100);'
              SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'MobileNumber VARCHAR(100);'
              SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'WorkNumber VARCHAR(100);'
              SET @Seq +=1
              END

              EXEC (@SQLString)

              --Update additional person details
              SET @SQLString=''

              SET @Seq=2
              WHILE @MaxPerson>=@Seq
              BEGIN
              SET @SQLString=@SQLString+CHAR(13)+'UPDATE #CaseList SET Person'+CAST(@Seq AS VARCHAR)+'FirstName =CT.FirstName
              ,Person'+CAST(@Seq AS VARCHAR)+'LastName =CT.LastName
              ,Person'+CAST(@Seq AS VARCHAR)+'HomeNumber =CT.HomeNumber
              ,Person'+CAST(@Seq AS VARCHAR)+'MobileNumber=CT.MobileNumber
              ,Person'+CAST(@Seq AS VARCHAR)+'WorkNumber =CT.WorkNumber
              FROM #CaseTemp CT
              WHERE #CaseList.CaseNumber=CT.CaseNumber AND CT.RowNumber='+CAST(@Seq AS VARCHAR)+''
              SET @Seq +=1
              END

              EXEC (@SQLString)

              --SELECT * FROM #CaseTemp
              SELECT * FROM #CaseList





              share|improve this answer




























                0














                you can check the following script. I have added dynamic table which is related with maximum person added to the CasePersons table for each case.



                /*
                DROP TABLE #Case;
                DROP TABLE #CasePersons;
                DROP TABLE #CaseDetails;
                DROP TABLE #CaseTemp;
                */
                CREATE TABLE #Case
                (
                CaseNumber INT
                ,CaseOwner VARCHAR(100)
                );

                INSERT INTO #Case VALUES(1,'Owner1'),(2,'Owner2'),(3,'Owner3');

                CREATE TABLE #CasePersons
                (
                PersonId INT
                ,CaseNumber INT
                ,FirstName VARCHAR(100)
                ,LastName VARCHAR(100)
                );

                INSERT INTO #CasePersons
                VALUES(1,1,'Bob','Person'),(2,1,'Jim','Human'),(3,2,'Gary','Man'),(4,3,'Pete','Smith'),(5,3,'Matt','Jones');

                CREATE TABLE #CaseDetails
                (
                PersonId INT
                ,Detail VARCHAR(100)
                ,[TYPE] INT
                );

                INSERT INTO #CaseDetails
                VALUES
                (1,'0123456789',1)
                ,(1,'1111111111',2)
                ,(2,'2222222222',1)
                ,(1,'0101001011',3)
                ,(2,'1234123412',2)
                ,(3,'0000011111',1)
                ,(3,'1231231231',2);



                SELECT c.CaseNumber
                ,c.CaseOwner
                ,ROW_NUMBER() OVER (PARTITION BY C.CaseNumber ORDER BY CD.PersonId) RowNumber
                ,CP.PersonId
                ,CP.FirstName
                ,CP.LastName
                ,CD.HomeNumber
                ,CD.MobileNumber
                ,CD.WorkNumber
                INTO #CaseTemp
                FROM #Case C
                LEFT JOIN #CasePersons CP ON C.CaseNumber = CP.CaseNumber
                LEFT JOIN
                (
                SELECT PersonId
                ,MAX(CASE WHEN TYPE=1 THEN Detail END) HomeNumber
                ,MAX(CASE WHEN TYPE=2 THEN Detail END) MobileNumber
                ,MAX(CASE WHEN TYPE=3 THEN Detail END) WorkNumber
                FROM #CaseDetails
                GROUP BY PersonId
                ) CD ON CP.PersonId = CD.PersonId
                --WHERE CD.TYPE=1
                ORDER BY C.CaseNumber
                ,CP.PersonId

                --Create result table
                DROP TABLE #CaseList
                GO
                CREATE TABLE #CaseList
                (
                CaseNumber INT
                ,CaseOwner VARCHAR(100)
                ,Person1FirstName VARCHAR(100)
                ,Person1LastName VARCHAR(100)
                ,Person1HomeNumber VARCHAR(100)
                ,Person1MobileNumber VARCHAR(100)
                ,Person1WorkNumber VARCHAR(100)
                )

                --Insert first person details to the table
                INSERT INTO #CaseList
                SELECT CaseNumber
                ,CaseOwner
                ,FirstName
                ,LastName
                ,HomeNumber
                ,MobileNumber
                ,WorkNumber
                FROM #CaseTemp
                WHERE RowNumber=1

                --Create additional person fields
                DECLARE @SQLString VARCHAR(MAX)=''
                DECLARE @MaxPerson INT=(SELECT MAX(RowNumber) FROM #CaseTemp)
                DECLARE @Seq int=2

                --
                WHILE @MaxPerson>=@Seq
                BEGIN
                SET @SQLString='ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'FirstName VARCHAR(100);'
                SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'LastName VARCHAR(100);'
                SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'HomeNumber VARCHAR(100);'
                SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'MobileNumber VARCHAR(100);'
                SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'WorkNumber VARCHAR(100);'
                SET @Seq +=1
                END

                EXEC (@SQLString)

                --Update additional person details
                SET @SQLString=''

                SET @Seq=2
                WHILE @MaxPerson>=@Seq
                BEGIN
                SET @SQLString=@SQLString+CHAR(13)+'UPDATE #CaseList SET Person'+CAST(@Seq AS VARCHAR)+'FirstName =CT.FirstName
                ,Person'+CAST(@Seq AS VARCHAR)+'LastName =CT.LastName
                ,Person'+CAST(@Seq AS VARCHAR)+'HomeNumber =CT.HomeNumber
                ,Person'+CAST(@Seq AS VARCHAR)+'MobileNumber=CT.MobileNumber
                ,Person'+CAST(@Seq AS VARCHAR)+'WorkNumber =CT.WorkNumber
                FROM #CaseTemp CT
                WHERE #CaseList.CaseNumber=CT.CaseNumber AND CT.RowNumber='+CAST(@Seq AS VARCHAR)+''
                SET @Seq +=1
                END

                EXEC (@SQLString)

                --SELECT * FROM #CaseTemp
                SELECT * FROM #CaseList





                share|improve this answer


























                  0












                  0








                  0







                  you can check the following script. I have added dynamic table which is related with maximum person added to the CasePersons table for each case.



                  /*
                  DROP TABLE #Case;
                  DROP TABLE #CasePersons;
                  DROP TABLE #CaseDetails;
                  DROP TABLE #CaseTemp;
                  */
                  CREATE TABLE #Case
                  (
                  CaseNumber INT
                  ,CaseOwner VARCHAR(100)
                  );

                  INSERT INTO #Case VALUES(1,'Owner1'),(2,'Owner2'),(3,'Owner3');

                  CREATE TABLE #CasePersons
                  (
                  PersonId INT
                  ,CaseNumber INT
                  ,FirstName VARCHAR(100)
                  ,LastName VARCHAR(100)
                  );

                  INSERT INTO #CasePersons
                  VALUES(1,1,'Bob','Person'),(2,1,'Jim','Human'),(3,2,'Gary','Man'),(4,3,'Pete','Smith'),(5,3,'Matt','Jones');

                  CREATE TABLE #CaseDetails
                  (
                  PersonId INT
                  ,Detail VARCHAR(100)
                  ,[TYPE] INT
                  );

                  INSERT INTO #CaseDetails
                  VALUES
                  (1,'0123456789',1)
                  ,(1,'1111111111',2)
                  ,(2,'2222222222',1)
                  ,(1,'0101001011',3)
                  ,(2,'1234123412',2)
                  ,(3,'0000011111',1)
                  ,(3,'1231231231',2);



                  SELECT c.CaseNumber
                  ,c.CaseOwner
                  ,ROW_NUMBER() OVER (PARTITION BY C.CaseNumber ORDER BY CD.PersonId) RowNumber
                  ,CP.PersonId
                  ,CP.FirstName
                  ,CP.LastName
                  ,CD.HomeNumber
                  ,CD.MobileNumber
                  ,CD.WorkNumber
                  INTO #CaseTemp
                  FROM #Case C
                  LEFT JOIN #CasePersons CP ON C.CaseNumber = CP.CaseNumber
                  LEFT JOIN
                  (
                  SELECT PersonId
                  ,MAX(CASE WHEN TYPE=1 THEN Detail END) HomeNumber
                  ,MAX(CASE WHEN TYPE=2 THEN Detail END) MobileNumber
                  ,MAX(CASE WHEN TYPE=3 THEN Detail END) WorkNumber
                  FROM #CaseDetails
                  GROUP BY PersonId
                  ) CD ON CP.PersonId = CD.PersonId
                  --WHERE CD.TYPE=1
                  ORDER BY C.CaseNumber
                  ,CP.PersonId

                  --Create result table
                  DROP TABLE #CaseList
                  GO
                  CREATE TABLE #CaseList
                  (
                  CaseNumber INT
                  ,CaseOwner VARCHAR(100)
                  ,Person1FirstName VARCHAR(100)
                  ,Person1LastName VARCHAR(100)
                  ,Person1HomeNumber VARCHAR(100)
                  ,Person1MobileNumber VARCHAR(100)
                  ,Person1WorkNumber VARCHAR(100)
                  )

                  --Insert first person details to the table
                  INSERT INTO #CaseList
                  SELECT CaseNumber
                  ,CaseOwner
                  ,FirstName
                  ,LastName
                  ,HomeNumber
                  ,MobileNumber
                  ,WorkNumber
                  FROM #CaseTemp
                  WHERE RowNumber=1

                  --Create additional person fields
                  DECLARE @SQLString VARCHAR(MAX)=''
                  DECLARE @MaxPerson INT=(SELECT MAX(RowNumber) FROM #CaseTemp)
                  DECLARE @Seq int=2

                  --
                  WHILE @MaxPerson>=@Seq
                  BEGIN
                  SET @SQLString='ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'FirstName VARCHAR(100);'
                  SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'LastName VARCHAR(100);'
                  SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'HomeNumber VARCHAR(100);'
                  SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'MobileNumber VARCHAR(100);'
                  SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'WorkNumber VARCHAR(100);'
                  SET @Seq +=1
                  END

                  EXEC (@SQLString)

                  --Update additional person details
                  SET @SQLString=''

                  SET @Seq=2
                  WHILE @MaxPerson>=@Seq
                  BEGIN
                  SET @SQLString=@SQLString+CHAR(13)+'UPDATE #CaseList SET Person'+CAST(@Seq AS VARCHAR)+'FirstName =CT.FirstName
                  ,Person'+CAST(@Seq AS VARCHAR)+'LastName =CT.LastName
                  ,Person'+CAST(@Seq AS VARCHAR)+'HomeNumber =CT.HomeNumber
                  ,Person'+CAST(@Seq AS VARCHAR)+'MobileNumber=CT.MobileNumber
                  ,Person'+CAST(@Seq AS VARCHAR)+'WorkNumber =CT.WorkNumber
                  FROM #CaseTemp CT
                  WHERE #CaseList.CaseNumber=CT.CaseNumber AND CT.RowNumber='+CAST(@Seq AS VARCHAR)+''
                  SET @Seq +=1
                  END

                  EXEC (@SQLString)

                  --SELECT * FROM #CaseTemp
                  SELECT * FROM #CaseList





                  share|improve this answer













                  you can check the following script. I have added dynamic table which is related with maximum person added to the CasePersons table for each case.



                  /*
                  DROP TABLE #Case;
                  DROP TABLE #CasePersons;
                  DROP TABLE #CaseDetails;
                  DROP TABLE #CaseTemp;
                  */
                  CREATE TABLE #Case
                  (
                  CaseNumber INT
                  ,CaseOwner VARCHAR(100)
                  );

                  INSERT INTO #Case VALUES(1,'Owner1'),(2,'Owner2'),(3,'Owner3');

                  CREATE TABLE #CasePersons
                  (
                  PersonId INT
                  ,CaseNumber INT
                  ,FirstName VARCHAR(100)
                  ,LastName VARCHAR(100)
                  );

                  INSERT INTO #CasePersons
                  VALUES(1,1,'Bob','Person'),(2,1,'Jim','Human'),(3,2,'Gary','Man'),(4,3,'Pete','Smith'),(5,3,'Matt','Jones');

                  CREATE TABLE #CaseDetails
                  (
                  PersonId INT
                  ,Detail VARCHAR(100)
                  ,[TYPE] INT
                  );

                  INSERT INTO #CaseDetails
                  VALUES
                  (1,'0123456789',1)
                  ,(1,'1111111111',2)
                  ,(2,'2222222222',1)
                  ,(1,'0101001011',3)
                  ,(2,'1234123412',2)
                  ,(3,'0000011111',1)
                  ,(3,'1231231231',2);



                  SELECT c.CaseNumber
                  ,c.CaseOwner
                  ,ROW_NUMBER() OVER (PARTITION BY C.CaseNumber ORDER BY CD.PersonId) RowNumber
                  ,CP.PersonId
                  ,CP.FirstName
                  ,CP.LastName
                  ,CD.HomeNumber
                  ,CD.MobileNumber
                  ,CD.WorkNumber
                  INTO #CaseTemp
                  FROM #Case C
                  LEFT JOIN #CasePersons CP ON C.CaseNumber = CP.CaseNumber
                  LEFT JOIN
                  (
                  SELECT PersonId
                  ,MAX(CASE WHEN TYPE=1 THEN Detail END) HomeNumber
                  ,MAX(CASE WHEN TYPE=2 THEN Detail END) MobileNumber
                  ,MAX(CASE WHEN TYPE=3 THEN Detail END) WorkNumber
                  FROM #CaseDetails
                  GROUP BY PersonId
                  ) CD ON CP.PersonId = CD.PersonId
                  --WHERE CD.TYPE=1
                  ORDER BY C.CaseNumber
                  ,CP.PersonId

                  --Create result table
                  DROP TABLE #CaseList
                  GO
                  CREATE TABLE #CaseList
                  (
                  CaseNumber INT
                  ,CaseOwner VARCHAR(100)
                  ,Person1FirstName VARCHAR(100)
                  ,Person1LastName VARCHAR(100)
                  ,Person1HomeNumber VARCHAR(100)
                  ,Person1MobileNumber VARCHAR(100)
                  ,Person1WorkNumber VARCHAR(100)
                  )

                  --Insert first person details to the table
                  INSERT INTO #CaseList
                  SELECT CaseNumber
                  ,CaseOwner
                  ,FirstName
                  ,LastName
                  ,HomeNumber
                  ,MobileNumber
                  ,WorkNumber
                  FROM #CaseTemp
                  WHERE RowNumber=1

                  --Create additional person fields
                  DECLARE @SQLString VARCHAR(MAX)=''
                  DECLARE @MaxPerson INT=(SELECT MAX(RowNumber) FROM #CaseTemp)
                  DECLARE @Seq int=2

                  --
                  WHILE @MaxPerson>=@Seq
                  BEGIN
                  SET @SQLString='ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'FirstName VARCHAR(100);'
                  SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'LastName VARCHAR(100);'
                  SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'HomeNumber VARCHAR(100);'
                  SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'MobileNumber VARCHAR(100);'
                  SET @SQLString=@SQLString+CHAR(13)+'ALTER TABLE #CaseList ADD Person'+CAST(@Seq AS VARCHAR)+'WorkNumber VARCHAR(100);'
                  SET @Seq +=1
                  END

                  EXEC (@SQLString)

                  --Update additional person details
                  SET @SQLString=''

                  SET @Seq=2
                  WHILE @MaxPerson>=@Seq
                  BEGIN
                  SET @SQLString=@SQLString+CHAR(13)+'UPDATE #CaseList SET Person'+CAST(@Seq AS VARCHAR)+'FirstName =CT.FirstName
                  ,Person'+CAST(@Seq AS VARCHAR)+'LastName =CT.LastName
                  ,Person'+CAST(@Seq AS VARCHAR)+'HomeNumber =CT.HomeNumber
                  ,Person'+CAST(@Seq AS VARCHAR)+'MobileNumber=CT.MobileNumber
                  ,Person'+CAST(@Seq AS VARCHAR)+'WorkNumber =CT.WorkNumber
                  FROM #CaseTemp CT
                  WHERE #CaseList.CaseNumber=CT.CaseNumber AND CT.RowNumber='+CAST(@Seq AS VARCHAR)+''
                  SET @Seq +=1
                  END

                  EXEC (@SQLString)

                  --SELECT * FROM #CaseTemp
                  SELECT * FROM #CaseList






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 19 '18 at 14:49









                  Zeki GumusZeki Gumus

                  1,382212




                  1,382212






























                      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.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53375775%2fextracting-multiple-rows-from-a-table-with-two-linked-tables-in-sql-server%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

                      鏡平學校

                      ꓛꓣだゔៀៅຸ໢ທຮ໕໒ ,ໂ'໥໓າ໼ឨឲ៵៭ៈゎゔit''䖳𥁄卿' ☨₤₨こゎもょの;ꜹꟚꞖꞵꟅꞛေၦေɯ,ɨɡ𛃵𛁹ޝ޳ޠ޾,ޤޒޯ޾𫝒𫠁သ𛅤チョ'サノބޘދ𛁐ᶿᶇᶀᶋᶠ㨑㽹⻮ꧬ꧹؍۩وَؠ㇕㇃㇪ ㇦㇋㇋ṜẰᵡᴠ 軌ᵕ搜۳ٰޗޮ޷ސޯ𫖾𫅀ल, ꙭ꙰ꚅꙁꚊꞻꝔ꟠Ꝭㄤﺟޱސꧨꧼ꧴ꧯꧽ꧲ꧯ'⽹⽭⾁⿞⼳⽋២៩ញណើꩯꩤ꩸ꩮᶻᶺᶧᶂ𫳲𫪭𬸄𫵰𬖩𬫣𬊉ၲ𛅬㕦䬺𫝌𫝼,,𫟖𫞽ហៅ஫㆔ాఆఅꙒꚞꙍ,Ꙟ꙱エ ,ポテ,フࢰࢯ𫟠𫞶 𫝤𫟠ﺕﹱﻜﻣ𪵕𪭸𪻆𪾩𫔷ġ,ŧآꞪ꟥,ꞔꝻ♚☹⛵𛀌ꬷꭞȄƁƪƬșƦǙǗdžƝǯǧⱦⱰꓕꓢႋ神 ဴ၀க௭எ௫ឫោ ' េㇷㇴㇼ神ㇸㇲㇽㇴㇼㇻㇸ'ㇸㇿㇸㇹㇰㆣꓚꓤ₡₧ ㄨㄟ㄂ㄖㄎ໗ツڒذ₶।ऩछएोञयूटक़कयँृी,冬'𛅢𛅥ㇱㇵㇶ𥄥𦒽𠣧𠊓𧢖𥞘𩔋цѰㄠſtʯʭɿʆʗʍʩɷɛ,əʏダヵㄐㄘR{gỚṖḺờṠṫảḙḭᴮᵏᴘᵀᵷᵕᴜᴏᵾq﮲ﲿﴽﭙ軌ﰬﶚﶧ﫲Ҝжюїкӈㇴffצּ﬘﭅﬈軌'ffistfflſtffतभफɳɰʊɲʎ𛁱𛁖𛁮𛀉 𛂯𛀞నఋŀŲ 𫟲𫠖𫞺ຆຆ ໹້໕໗ๆทԊꧢꧠ꧰ꓱ⿝⼑ŎḬẃẖỐẅ ,ờỰỈỗﮊDžȩꭏꭎꬻ꭮ꬿꭖꭥꭅ㇭神 ⾈ꓵꓑ⺄㄄ㄪㄙㄅㄇstA۵䞽ॶ𫞑𫝄㇉㇇゜軌𩜛𩳠Jﻺ‚Üမ႕ႌႊၐၸဓၞၞၡ៸wyvtᶎᶪᶹစဎ꣡꣰꣢꣤ٗ؋لㇳㇾㇻㇱ㆐㆔,,㆟Ⱶヤマފ޼ޝަݿݞݠݷݐ',ݘ,ݪݙݵ𬝉𬜁𫝨𫞘くせぉて¼óû×ó£…𛅑הㄙくԗԀ5606神45,神796'𪤻𫞧ꓐ㄁ㄘɥɺꓵꓲ3''7034׉ⱦⱠˆ“𫝋ȍ,ꩲ軌꩷ꩶꩧꩫఞ۔فڱێظペサ神ナᴦᵑ47 9238їﻂ䐊䔉㠸﬎ffiﬣ,לּᴷᴦᵛᵽ,ᴨᵤ ᵸᵥᴗᵈꚏꚉꚟ⻆rtǟƴ𬎎

                      Why https connections are so slow when debugging (stepping over) in Java?