How can I make this SQL more Efficient











up vote
0
down vote

favorite












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 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 at 14:18















up vote
0
down vote

favorite












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 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 at 14:18













up vote
0
down vote

favorite









up vote
0
down vote

favorite











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 at 5:14









marc_s

566k12610941246




566k12610941246










asked Nov 22 at 0:08









Kush

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 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 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 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 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 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 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 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 at 14:18












2 Answers
2






active

oldest

votes

















up vote
3
down vote













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




























    up vote
    0
    down vote













    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',
      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








      up vote
      3
      down vote













      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

























        up vote
        3
        down vote













        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























          up vote
          3
          down vote










          up vote
          3
          down vote









          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 at 0:20









          Tim Biegeleisen

          210k1381129




          210k1381129
























              up vote
              0
              down vote













              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

























                up vote
                0
                down vote













                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























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  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 at 0:30









                  Gordon Linoff

                  747k34285390




                  747k34285390






























                       

                      draft saved


                      draft discarded



















































                       


                      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

                      What visual should I use to simply compare current year value vs last year in Power BI desktop

                      How to ignore python UserWarning in pytest?

                      Alexandru Averescu