How can I make this SQL more Efficient












0















I have written this piece of SQL, I know there are ways to make it run faster, with the right practices.



SELECT DISTINCT
ACCOUNTNUM,
FIRSTNAME AS NAME,
LASTNAME AS SURNAME,
(PHONE + ' ' + CELLULARPHONE) AS PHONENUM,
EMAIL,
(SELECT TOP 1 CREATEDDATE
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM
ORDER BY CREATEDDATE DESC) AS LASTVISIT, -- LAST VISIT,
(SELECT COUNT(TRANSACTIONID)
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALVISITS, -- TOTAL VISITS,
(SELECT SUM(PAYMENTAMOUNT)
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALSALES, -- TOTAL SALES,
(SELECT SUM(DISCAMOUNT)
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM) AS DISCOUNT
FROM
CUSTOMER
LEFT OUTER JOIN
RBOTRANSACTIONTABLE ON CUSTACCOUNT = ACCOUNTNUM


I know if I am using some sort of Joins, I don't have necessarily have to keep saying FROM RBOTRANSACTIONTABLE every time (the code after Email column). The code above works great for my requirement, but I know there are missing gaps in my knowledge, I just don't know what.



I am looking for in-depth answers as to why the above solution is not recommended, and why your solution is.










share|improve this question




















  • 1





    It's helpful to tag database questions with both the appropriate software (MySQL, Oracle, DB2, ...) and version, e.g. sql-server-2014. Differences in syntax and features often affect the answers. Note that tsql narrows the choices, but does not specify the database. Assuming that you are using SQL Server: See paste the plan for a way to include an execution plan in your question.

    – HABO
    Nov 22 '18 at 1:12






  • 1





    You used DISTINCT to cover up your logic error. There is NO reason to join Customer and Transaction when you do the equivalent as subqueries. And you used 4 separate subqueries to the same table for your calculations, each of which is a simple aggregate. That should have been a clue that you could calculate all 4 values with a single pass through the transaction table - as Tim demonstrates. lastly - [top 1 x order by x desc] is the same as max(). The latter is far more readable, more understandable, and less prone to error.

    – SMor
    Nov 22 '18 at 14:18
















0















I have written this piece of SQL, I know there are ways to make it run faster, with the right practices.



SELECT DISTINCT
ACCOUNTNUM,
FIRSTNAME AS NAME,
LASTNAME AS SURNAME,
(PHONE + ' ' + CELLULARPHONE) AS PHONENUM,
EMAIL,
(SELECT TOP 1 CREATEDDATE
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM
ORDER BY CREATEDDATE DESC) AS LASTVISIT, -- LAST VISIT,
(SELECT COUNT(TRANSACTIONID)
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALVISITS, -- TOTAL VISITS,
(SELECT SUM(PAYMENTAMOUNT)
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALSALES, -- TOTAL SALES,
(SELECT SUM(DISCAMOUNT)
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM) AS DISCOUNT
FROM
CUSTOMER
LEFT OUTER JOIN
RBOTRANSACTIONTABLE ON CUSTACCOUNT = ACCOUNTNUM


I know if I am using some sort of Joins, I don't have necessarily have to keep saying FROM RBOTRANSACTIONTABLE every time (the code after Email column). The code above works great for my requirement, but I know there are missing gaps in my knowledge, I just don't know what.



I am looking for in-depth answers as to why the above solution is not recommended, and why your solution is.










share|improve this question




















  • 1





    It's helpful to tag database questions with both the appropriate software (MySQL, Oracle, DB2, ...) and version, e.g. sql-server-2014. Differences in syntax and features often affect the answers. Note that tsql narrows the choices, but does not specify the database. Assuming that you are using SQL Server: See paste the plan for a way to include an execution plan in your question.

    – HABO
    Nov 22 '18 at 1:12






  • 1





    You used DISTINCT to cover up your logic error. There is NO reason to join Customer and Transaction when you do the equivalent as subqueries. And you used 4 separate subqueries to the same table for your calculations, each of which is a simple aggregate. That should have been a clue that you could calculate all 4 values with a single pass through the transaction table - as Tim demonstrates. lastly - [top 1 x order by x desc] is the same as max(). The latter is far more readable, more understandable, and less prone to error.

    – SMor
    Nov 22 '18 at 14:18














0












0








0








I have written this piece of SQL, I know there are ways to make it run faster, with the right practices.



SELECT DISTINCT
ACCOUNTNUM,
FIRSTNAME AS NAME,
LASTNAME AS SURNAME,
(PHONE + ' ' + CELLULARPHONE) AS PHONENUM,
EMAIL,
(SELECT TOP 1 CREATEDDATE
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM
ORDER BY CREATEDDATE DESC) AS LASTVISIT, -- LAST VISIT,
(SELECT COUNT(TRANSACTIONID)
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALVISITS, -- TOTAL VISITS,
(SELECT SUM(PAYMENTAMOUNT)
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALSALES, -- TOTAL SALES,
(SELECT SUM(DISCAMOUNT)
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM) AS DISCOUNT
FROM
CUSTOMER
LEFT OUTER JOIN
RBOTRANSACTIONTABLE ON CUSTACCOUNT = ACCOUNTNUM


I know if I am using some sort of Joins, I don't have necessarily have to keep saying FROM RBOTRANSACTIONTABLE every time (the code after Email column). The code above works great for my requirement, but I know there are missing gaps in my knowledge, I just don't know what.



I am looking for in-depth answers as to why the above solution is not recommended, and why your solution is.










share|improve this question
















I have written this piece of SQL, I know there are ways to make it run faster, with the right practices.



SELECT DISTINCT
ACCOUNTNUM,
FIRSTNAME AS NAME,
LASTNAME AS SURNAME,
(PHONE + ' ' + CELLULARPHONE) AS PHONENUM,
EMAIL,
(SELECT TOP 1 CREATEDDATE
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM
ORDER BY CREATEDDATE DESC) AS LASTVISIT, -- LAST VISIT,
(SELECT COUNT(TRANSACTIONID)
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALVISITS, -- TOTAL VISITS,
(SELECT SUM(PAYMENTAMOUNT)
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALSALES, -- TOTAL SALES,
(SELECT SUM(DISCAMOUNT)
FROM RBOTRANSACTIONTABLE
WHERE CUSTACCOUNT = ACCOUNTNUM) AS DISCOUNT
FROM
CUSTOMER
LEFT OUTER JOIN
RBOTRANSACTIONTABLE ON CUSTACCOUNT = ACCOUNTNUM


I know if I am using some sort of Joins, I don't have necessarily have to keep saying FROM RBOTRANSACTIONTABLE every time (the code after Email column). The code above works great for my requirement, but I know there are missing gaps in my knowledge, I just don't know what.



I am looking for in-depth answers as to why the above solution is not recommended, and why your solution is.







sql-server tsql relational-database






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 5:14









marc_s

572k12811061253




572k12811061253










asked Nov 22 '18 at 0:08









KushKush

97111




97111








  • 1





    It's helpful to tag database questions with both the appropriate software (MySQL, Oracle, DB2, ...) and version, e.g. sql-server-2014. Differences in syntax and features often affect the answers. Note that tsql narrows the choices, but does not specify the database. Assuming that you are using SQL Server: See paste the plan for a way to include an execution plan in your question.

    – HABO
    Nov 22 '18 at 1:12






  • 1





    You used DISTINCT to cover up your logic error. There is NO reason to join Customer and Transaction when you do the equivalent as subqueries. And you used 4 separate subqueries to the same table for your calculations, each of which is a simple aggregate. That should have been a clue that you could calculate all 4 values with a single pass through the transaction table - as Tim demonstrates. lastly - [top 1 x order by x desc] is the same as max(). The latter is far more readable, more understandable, and less prone to error.

    – SMor
    Nov 22 '18 at 14:18














  • 1





    It's helpful to tag database questions with both the appropriate software (MySQL, Oracle, DB2, ...) and version, e.g. sql-server-2014. Differences in syntax and features often affect the answers. Note that tsql narrows the choices, but does not specify the database. Assuming that you are using SQL Server: See paste the plan for a way to include an execution plan in your question.

    – HABO
    Nov 22 '18 at 1:12






  • 1





    You used DISTINCT to cover up your logic error. There is NO reason to join Customer and Transaction when you do the equivalent as subqueries. And you used 4 separate subqueries to the same table for your calculations, each of which is a simple aggregate. That should have been a clue that you could calculate all 4 values with a single pass through the transaction table - as Tim demonstrates. lastly - [top 1 x order by x desc] is the same as max(). The latter is far more readable, more understandable, and less prone to error.

    – SMor
    Nov 22 '18 at 14:18








1




1





It's helpful to tag database questions with both the appropriate software (MySQL, Oracle, DB2, ...) and version, e.g. sql-server-2014. Differences in syntax and features often affect the answers. Note that tsql narrows the choices, but does not specify the database. Assuming that you are using SQL Server: See paste the plan for a way to include an execution plan in your question.

– HABO
Nov 22 '18 at 1:12





It's helpful to tag database questions with both the appropriate software (MySQL, Oracle, DB2, ...) and version, e.g. sql-server-2014. Differences in syntax and features often affect the answers. Note that tsql narrows the choices, but does not specify the database. Assuming that you are using SQL Server: See paste the plan for a way to include an execution plan in your question.

– HABO
Nov 22 '18 at 1:12




1




1





You used DISTINCT to cover up your logic error. There is NO reason to join Customer and Transaction when you do the equivalent as subqueries. And you used 4 separate subqueries to the same table for your calculations, each of which is a simple aggregate. That should have been a clue that you could calculate all 4 values with a single pass through the transaction table - as Tim demonstrates. lastly - [top 1 x order by x desc] is the same as max(). The latter is far more readable, more understandable, and less prone to error.

– SMor
Nov 22 '18 at 14:18





You used DISTINCT to cover up your logic error. There is NO reason to join Customer and Transaction when you do the equivalent as subqueries. And you used 4 separate subqueries to the same table for your calculations, each of which is a simple aggregate. That should have been a clue that you could calculate all 4 values with a single pass through the transaction table - as Tim demonstrates. lastly - [top 1 x order by x desc] is the same as max(). The latter is far more readable, more understandable, and less prone to error.

– SMor
Nov 22 '18 at 14:18












2 Answers
2






active

oldest

votes


















3














You may rewrite your query as a join to a subquery which finds aggregates:



SELECT
c.ACCOUNTNUM,
c.FIRSTNAME AS NAME,
c.LASTNAME AS SURNAME,
(c.PHONE + ' ' + c.CELLULARPHONE) AS PHONENUM,
c.EMAIL,
a.LASTVISIT,
COALESCE(a.TOTALVISITS, 0) AS TOTALVISITS,
COALESCE(a.TOTALSALES, 0) AS TOTALSALES,
COALESCE(a.DISCOUNT, 0) AS DISCOUNT
FROM CUSTOMER c
LEFT JOIN
(
SELECT
CUSTACCOUNT,
MAX(CREATEDDATE) AS LASTVISIT,
COUNT(TRANSACTIONID) AS TOTALVISITS,
SUM(PAYMENTAMOUNT) AS TOTALSALES,
SUM(DISCAMOUNT) AS DISCOUNT
FROM RBOTRANSACTIONTABLE
GROUP BY CUSTACCOUNT
) a
ON c.ACCOUNTNUM = a.CUSTACCOUNT;


You should always use proper aliases when referring to columns in the SELECT clause.






share|improve this answer































    0














    Tim's is definitely a good way to rewrite the query. But you can also make your version more efficient by getting rid of the count(distinct) and outer join:



    SELECT ACCOUNTNUM,
    FIRSTNAME AS NAME,
    LASTNAME AS SURNAME,
    (PHONE + ' ' + CELLULARPHONE) AS PHONENUM,
    EMAIL,
    (SELECT TOP 1 CREATEDDATE FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM ORDER BY CREATEDDATE DESC) AS LASTVISIT, -- LAST VISIT,
    (SELECT COUNT(TRANSACTIONID) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALVISITS, -- TOTAL VISITS,
    (SELECT SUM(PAYMENTAMOUNT) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALSALES, -- TOTAL SALES,
    (SELECT SUM(DISCAMOUNT) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS DISCOUNT
    FROM CUSTOMER c;


    With the right indexes, this could even have better performance than the group by/join version.






    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%2f53422169%2fhow-can-i-make-this-sql-more-efficient%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      You may rewrite your query as a join to a subquery which finds aggregates:



      SELECT
      c.ACCOUNTNUM,
      c.FIRSTNAME AS NAME,
      c.LASTNAME AS SURNAME,
      (c.PHONE + ' ' + c.CELLULARPHONE) AS PHONENUM,
      c.EMAIL,
      a.LASTVISIT,
      COALESCE(a.TOTALVISITS, 0) AS TOTALVISITS,
      COALESCE(a.TOTALSALES, 0) AS TOTALSALES,
      COALESCE(a.DISCOUNT, 0) AS DISCOUNT
      FROM CUSTOMER c
      LEFT JOIN
      (
      SELECT
      CUSTACCOUNT,
      MAX(CREATEDDATE) AS LASTVISIT,
      COUNT(TRANSACTIONID) AS TOTALVISITS,
      SUM(PAYMENTAMOUNT) AS TOTALSALES,
      SUM(DISCAMOUNT) AS DISCOUNT
      FROM RBOTRANSACTIONTABLE
      GROUP BY CUSTACCOUNT
      ) a
      ON c.ACCOUNTNUM = a.CUSTACCOUNT;


      You should always use proper aliases when referring to columns in the SELECT clause.






      share|improve this answer




























        3














        You may rewrite your query as a join to a subquery which finds aggregates:



        SELECT
        c.ACCOUNTNUM,
        c.FIRSTNAME AS NAME,
        c.LASTNAME AS SURNAME,
        (c.PHONE + ' ' + c.CELLULARPHONE) AS PHONENUM,
        c.EMAIL,
        a.LASTVISIT,
        COALESCE(a.TOTALVISITS, 0) AS TOTALVISITS,
        COALESCE(a.TOTALSALES, 0) AS TOTALSALES,
        COALESCE(a.DISCOUNT, 0) AS DISCOUNT
        FROM CUSTOMER c
        LEFT JOIN
        (
        SELECT
        CUSTACCOUNT,
        MAX(CREATEDDATE) AS LASTVISIT,
        COUNT(TRANSACTIONID) AS TOTALVISITS,
        SUM(PAYMENTAMOUNT) AS TOTALSALES,
        SUM(DISCAMOUNT) AS DISCOUNT
        FROM RBOTRANSACTIONTABLE
        GROUP BY CUSTACCOUNT
        ) a
        ON c.ACCOUNTNUM = a.CUSTACCOUNT;


        You should always use proper aliases when referring to columns in the SELECT clause.






        share|improve this answer


























          3












          3








          3







          You may rewrite your query as a join to a subquery which finds aggregates:



          SELECT
          c.ACCOUNTNUM,
          c.FIRSTNAME AS NAME,
          c.LASTNAME AS SURNAME,
          (c.PHONE + ' ' + c.CELLULARPHONE) AS PHONENUM,
          c.EMAIL,
          a.LASTVISIT,
          COALESCE(a.TOTALVISITS, 0) AS TOTALVISITS,
          COALESCE(a.TOTALSALES, 0) AS TOTALSALES,
          COALESCE(a.DISCOUNT, 0) AS DISCOUNT
          FROM CUSTOMER c
          LEFT JOIN
          (
          SELECT
          CUSTACCOUNT,
          MAX(CREATEDDATE) AS LASTVISIT,
          COUNT(TRANSACTIONID) AS TOTALVISITS,
          SUM(PAYMENTAMOUNT) AS TOTALSALES,
          SUM(DISCAMOUNT) AS DISCOUNT
          FROM RBOTRANSACTIONTABLE
          GROUP BY CUSTACCOUNT
          ) a
          ON c.ACCOUNTNUM = a.CUSTACCOUNT;


          You should always use proper aliases when referring to columns in the SELECT clause.






          share|improve this answer













          You may rewrite your query as a join to a subquery which finds aggregates:



          SELECT
          c.ACCOUNTNUM,
          c.FIRSTNAME AS NAME,
          c.LASTNAME AS SURNAME,
          (c.PHONE + ' ' + c.CELLULARPHONE) AS PHONENUM,
          c.EMAIL,
          a.LASTVISIT,
          COALESCE(a.TOTALVISITS, 0) AS TOTALVISITS,
          COALESCE(a.TOTALSALES, 0) AS TOTALSALES,
          COALESCE(a.DISCOUNT, 0) AS DISCOUNT
          FROM CUSTOMER c
          LEFT JOIN
          (
          SELECT
          CUSTACCOUNT,
          MAX(CREATEDDATE) AS LASTVISIT,
          COUNT(TRANSACTIONID) AS TOTALVISITS,
          SUM(PAYMENTAMOUNT) AS TOTALSALES,
          SUM(DISCAMOUNT) AS DISCOUNT
          FROM RBOTRANSACTIONTABLE
          GROUP BY CUSTACCOUNT
          ) a
          ON c.ACCOUNTNUM = a.CUSTACCOUNT;


          You should always use proper aliases when referring to columns in the SELECT clause.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 '18 at 0:20









          Tim BiegeleisenTim Biegeleisen

          219k1388141




          219k1388141

























              0














              Tim's is definitely a good way to rewrite the query. But you can also make your version more efficient by getting rid of the count(distinct) and outer join:



              SELECT ACCOUNTNUM,
              FIRSTNAME AS NAME,
              LASTNAME AS SURNAME,
              (PHONE + ' ' + CELLULARPHONE) AS PHONENUM,
              EMAIL,
              (SELECT TOP 1 CREATEDDATE FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM ORDER BY CREATEDDATE DESC) AS LASTVISIT, -- LAST VISIT,
              (SELECT COUNT(TRANSACTIONID) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALVISITS, -- TOTAL VISITS,
              (SELECT SUM(PAYMENTAMOUNT) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALSALES, -- TOTAL SALES,
              (SELECT SUM(DISCAMOUNT) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS DISCOUNT
              FROM CUSTOMER c;


              With the right indexes, this could even have better performance than the group by/join version.






              share|improve this answer




























                0














                Tim's is definitely a good way to rewrite the query. But you can also make your version more efficient by getting rid of the count(distinct) and outer join:



                SELECT ACCOUNTNUM,
                FIRSTNAME AS NAME,
                LASTNAME AS SURNAME,
                (PHONE + ' ' + CELLULARPHONE) AS PHONENUM,
                EMAIL,
                (SELECT TOP 1 CREATEDDATE FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM ORDER BY CREATEDDATE DESC) AS LASTVISIT, -- LAST VISIT,
                (SELECT COUNT(TRANSACTIONID) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALVISITS, -- TOTAL VISITS,
                (SELECT SUM(PAYMENTAMOUNT) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALSALES, -- TOTAL SALES,
                (SELECT SUM(DISCAMOUNT) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS DISCOUNT
                FROM CUSTOMER c;


                With the right indexes, this could even have better performance than the group by/join version.






                share|improve this answer


























                  0












                  0








                  0







                  Tim's is definitely a good way to rewrite the query. But you can also make your version more efficient by getting rid of the count(distinct) and outer join:



                  SELECT ACCOUNTNUM,
                  FIRSTNAME AS NAME,
                  LASTNAME AS SURNAME,
                  (PHONE + ' ' + CELLULARPHONE) AS PHONENUM,
                  EMAIL,
                  (SELECT TOP 1 CREATEDDATE FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM ORDER BY CREATEDDATE DESC) AS LASTVISIT, -- LAST VISIT,
                  (SELECT COUNT(TRANSACTIONID) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALVISITS, -- TOTAL VISITS,
                  (SELECT SUM(PAYMENTAMOUNT) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALSALES, -- TOTAL SALES,
                  (SELECT SUM(DISCAMOUNT) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS DISCOUNT
                  FROM CUSTOMER c;


                  With the right indexes, this could even have better performance than the group by/join version.






                  share|improve this answer













                  Tim's is definitely a good way to rewrite the query. But you can also make your version more efficient by getting rid of the count(distinct) and outer join:



                  SELECT ACCOUNTNUM,
                  FIRSTNAME AS NAME,
                  LASTNAME AS SURNAME,
                  (PHONE + ' ' + CELLULARPHONE) AS PHONENUM,
                  EMAIL,
                  (SELECT TOP 1 CREATEDDATE FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM ORDER BY CREATEDDATE DESC) AS LASTVISIT, -- LAST VISIT,
                  (SELECT COUNT(TRANSACTIONID) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALVISITS, -- TOTAL VISITS,
                  (SELECT SUM(PAYMENTAMOUNT) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS TOTALSALES, -- TOTAL SALES,
                  (SELECT SUM(DISCAMOUNT) FROM RBOTRANSACTIONTABLE WHERE CUSTACCOUNT = ACCOUNTNUM) AS DISCOUNT
                  FROM CUSTOMER c;


                  With the right indexes, this could even have better performance than the group by/join version.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 22 '18 at 0:30









                  Gordon LinoffGordon Linoff

                  762k35296400




                  762k35296400






























                      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%2f53422169%2fhow-can-i-make-this-sql-more-efficient%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

                      404 Error Contact Form 7 ajax form submitting

                      How to know if a Active Directory user can login interactively

                      TypeError: fit_transform() missing 1 required positional argument: 'X'