SQL Server Match Closest Record With Another Table





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I have two tables, one with the time a customer spoke with a colleague and another where they have made a purchase however I can't figure out how to tie the closest purchase to a particular colleague



For example



Table 1 - Colleague Interactions



[ColleagueID]  [DateOfInteraction]  [CustomerID]
------------------------------------------------
A 2018-11-22 12:00 123
B 2018-11-22 12:02 123


Table 2 - List of Purchases



[PurchaseID]  [DateOfPurchase]  [PurchaseOutcome]  [CustomerID]
----------------------------------------------------------------
1 2018-11-22 12:01 FAIL 123
2 2018-11-22 12:03 SUCCESS 123


What I want to do with the above is to tie these two records together, initially I do this on the CustomerID but this obviously create duplication as the customerID appears twice in Table 2 and Table 1. I then try to narrow to say where DateOfInteraction < DateOfPurchase which will eliminate the first record however I am unsure on how to match the second?



The results should look like



[ColleagueID]  [DateOfInteraction]  [CustomerID]  [PurchaseID]  [DateOfPurchase]  [PurchaseOutcome]
---------------------------------------------------------------------------------------------------
A 2018-11-22 12:00 123 1 2018-11-22 12:01 FAIL
B 2018-11-22 12:02 123 2 2018-11-22 12:03 SUCCESS









share|improve this question































    1















    I have two tables, one with the time a customer spoke with a colleague and another where they have made a purchase however I can't figure out how to tie the closest purchase to a particular colleague



    For example



    Table 1 - Colleague Interactions



    [ColleagueID]  [DateOfInteraction]  [CustomerID]
    ------------------------------------------------
    A 2018-11-22 12:00 123
    B 2018-11-22 12:02 123


    Table 2 - List of Purchases



    [PurchaseID]  [DateOfPurchase]  [PurchaseOutcome]  [CustomerID]
    ----------------------------------------------------------------
    1 2018-11-22 12:01 FAIL 123
    2 2018-11-22 12:03 SUCCESS 123


    What I want to do with the above is to tie these two records together, initially I do this on the CustomerID but this obviously create duplication as the customerID appears twice in Table 2 and Table 1. I then try to narrow to say where DateOfInteraction < DateOfPurchase which will eliminate the first record however I am unsure on how to match the second?



    The results should look like



    [ColleagueID]  [DateOfInteraction]  [CustomerID]  [PurchaseID]  [DateOfPurchase]  [PurchaseOutcome]
    ---------------------------------------------------------------------------------------------------
    A 2018-11-22 12:00 123 1 2018-11-22 12:01 FAIL
    B 2018-11-22 12:02 123 2 2018-11-22 12:03 SUCCESS









    share|improve this question



























      1












      1








      1








      I have two tables, one with the time a customer spoke with a colleague and another where they have made a purchase however I can't figure out how to tie the closest purchase to a particular colleague



      For example



      Table 1 - Colleague Interactions



      [ColleagueID]  [DateOfInteraction]  [CustomerID]
      ------------------------------------------------
      A 2018-11-22 12:00 123
      B 2018-11-22 12:02 123


      Table 2 - List of Purchases



      [PurchaseID]  [DateOfPurchase]  [PurchaseOutcome]  [CustomerID]
      ----------------------------------------------------------------
      1 2018-11-22 12:01 FAIL 123
      2 2018-11-22 12:03 SUCCESS 123


      What I want to do with the above is to tie these two records together, initially I do this on the CustomerID but this obviously create duplication as the customerID appears twice in Table 2 and Table 1. I then try to narrow to say where DateOfInteraction < DateOfPurchase which will eliminate the first record however I am unsure on how to match the second?



      The results should look like



      [ColleagueID]  [DateOfInteraction]  [CustomerID]  [PurchaseID]  [DateOfPurchase]  [PurchaseOutcome]
      ---------------------------------------------------------------------------------------------------
      A 2018-11-22 12:00 123 1 2018-11-22 12:01 FAIL
      B 2018-11-22 12:02 123 2 2018-11-22 12:03 SUCCESS









      share|improve this question
















      I have two tables, one with the time a customer spoke with a colleague and another where they have made a purchase however I can't figure out how to tie the closest purchase to a particular colleague



      For example



      Table 1 - Colleague Interactions



      [ColleagueID]  [DateOfInteraction]  [CustomerID]
      ------------------------------------------------
      A 2018-11-22 12:00 123
      B 2018-11-22 12:02 123


      Table 2 - List of Purchases



      [PurchaseID]  [DateOfPurchase]  [PurchaseOutcome]  [CustomerID]
      ----------------------------------------------------------------
      1 2018-11-22 12:01 FAIL 123
      2 2018-11-22 12:03 SUCCESS 123


      What I want to do with the above is to tie these two records together, initially I do this on the CustomerID but this obviously create duplication as the customerID appears twice in Table 2 and Table 1. I then try to narrow to say where DateOfInteraction < DateOfPurchase which will eliminate the first record however I am unsure on how to match the second?



      The results should look like



      [ColleagueID]  [DateOfInteraction]  [CustomerID]  [PurchaseID]  [DateOfPurchase]  [PurchaseOutcome]
      ---------------------------------------------------------------------------------------------------
      A 2018-11-22 12:00 123 1 2018-11-22 12:01 FAIL
      B 2018-11-22 12:02 123 2 2018-11-22 12:03 SUCCESS






      sql-server tsql






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 24 at 13:30









      Cœur

      19.4k10116155




      19.4k10116155










      asked Nov 24 '18 at 14:50









      ChrisChris

      1,18211632




      1,18211632
























          1 Answer
          1






          active

          oldest

          votes


















          1














          I think apply does what you want:



          select p.*, i.*
          from purchases p outer apply
          (select top (1) i.*
          from interactions i
          where i.customer_id = p.customer_id and
          i.DateOfInteraction < p.DateOfPurhase
          order by i.DateOfInteraction desc
          ) i;





          share|improve this answer
























          • hey, sorry thought this was the answer, issue is that Top (1) bit doesn't work as that sub query is still returning 3 rows, 2 for the first colleague(because both interactions are less than the purchase date) so I end up with the same colleague for both purchases?

            – Chris
            Nov 24 '18 at 15:37











          • missed the order by desc, working now :) thanks

            – Chris
            Nov 24 '18 at 15:40












          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%2f53459350%2fsql-server-match-closest-record-with-another-table%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









          1














          I think apply does what you want:



          select p.*, i.*
          from purchases p outer apply
          (select top (1) i.*
          from interactions i
          where i.customer_id = p.customer_id and
          i.DateOfInteraction < p.DateOfPurhase
          order by i.DateOfInteraction desc
          ) i;





          share|improve this answer
























          • hey, sorry thought this was the answer, issue is that Top (1) bit doesn't work as that sub query is still returning 3 rows, 2 for the first colleague(because both interactions are less than the purchase date) so I end up with the same colleague for both purchases?

            – Chris
            Nov 24 '18 at 15:37











          • missed the order by desc, working now :) thanks

            – Chris
            Nov 24 '18 at 15:40
















          1














          I think apply does what you want:



          select p.*, i.*
          from purchases p outer apply
          (select top (1) i.*
          from interactions i
          where i.customer_id = p.customer_id and
          i.DateOfInteraction < p.DateOfPurhase
          order by i.DateOfInteraction desc
          ) i;





          share|improve this answer
























          • hey, sorry thought this was the answer, issue is that Top (1) bit doesn't work as that sub query is still returning 3 rows, 2 for the first colleague(because both interactions are less than the purchase date) so I end up with the same colleague for both purchases?

            – Chris
            Nov 24 '18 at 15:37











          • missed the order by desc, working now :) thanks

            – Chris
            Nov 24 '18 at 15:40














          1












          1








          1







          I think apply does what you want:



          select p.*, i.*
          from purchases p outer apply
          (select top (1) i.*
          from interactions i
          where i.customer_id = p.customer_id and
          i.DateOfInteraction < p.DateOfPurhase
          order by i.DateOfInteraction desc
          ) i;





          share|improve this answer













          I think apply does what you want:



          select p.*, i.*
          from purchases p outer apply
          (select top (1) i.*
          from interactions i
          where i.customer_id = p.customer_id and
          i.DateOfInteraction < p.DateOfPurhase
          order by i.DateOfInteraction desc
          ) i;






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 24 '18 at 14:54









          Gordon LinoffGordon Linoff

          799k37321426




          799k37321426













          • hey, sorry thought this was the answer, issue is that Top (1) bit doesn't work as that sub query is still returning 3 rows, 2 for the first colleague(because both interactions are less than the purchase date) so I end up with the same colleague for both purchases?

            – Chris
            Nov 24 '18 at 15:37











          • missed the order by desc, working now :) thanks

            – Chris
            Nov 24 '18 at 15:40



















          • hey, sorry thought this was the answer, issue is that Top (1) bit doesn't work as that sub query is still returning 3 rows, 2 for the first colleague(because both interactions are less than the purchase date) so I end up with the same colleague for both purchases?

            – Chris
            Nov 24 '18 at 15:37











          • missed the order by desc, working now :) thanks

            – Chris
            Nov 24 '18 at 15:40

















          hey, sorry thought this was the answer, issue is that Top (1) bit doesn't work as that sub query is still returning 3 rows, 2 for the first colleague(because both interactions are less than the purchase date) so I end up with the same colleague for both purchases?

          – Chris
          Nov 24 '18 at 15:37





          hey, sorry thought this was the answer, issue is that Top (1) bit doesn't work as that sub query is still returning 3 rows, 2 for the first colleague(because both interactions are less than the purchase date) so I end up with the same colleague for both purchases?

          – Chris
          Nov 24 '18 at 15:37













          missed the order by desc, working now :) thanks

          – Chris
          Nov 24 '18 at 15:40





          missed the order by desc, working now :) thanks

          – Chris
          Nov 24 '18 at 15:40




















          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%2f53459350%2fsql-server-match-closest-record-with-another-table%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







          這個網誌中的熱門文章

          Tangent Lines Diagram Along Smooth Curve

          Yusuf al-Mu'taman ibn Hud

          Zucchini