Calculate MTD using CTE and Projected Sales in SQL









up vote
1
down vote

favorite












I am trying to add MTD Sales in a SQL Query. I figured out how to do that with JOINS but i want to use a CTE to calculate MTD sales and then use that to calculate projected_sales.Formula for projected sales is (MTD/wkdaysinmonth*wkdaystodate)[which is also stored in CTE Table). Is there a way to make it easy? I wrote the following code;



Input:



Email PaymentAmount orderdate
xyz@gmail.com 10 11/01/2018
xyz@gmail.com 20 11/09/2018


sample output:



EmailAddress MTD Projected_sales
xyz@gmail.com 30 0.19


where Projected sales is calculated as number of days passed=7 and total number of business days in november 22. [30/7*22]=0.19 (Present date = 11/09/2018)



with dates as(
select dateadd(d,-day(getdate())+1,convert(date,getdate())) as startofmonth,
dateadd(d,-1,dateadd(m,1,dateadd(d,-day(getdate())+1,convert(date,getdate())))) as endofmonth,
convert(date,getdate()) as today
)
,daycounts as(
select dates.*,

(DATEDIFF(dd, startofmonth, endofmonth) + 1)
-(DATEDIFF(wk, startofmonth, endofmonth) * 2)
-(CASE WHEN DATENAME(dw, startofmonth) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, endofmonth) = 'Saturday' THEN 1 ELSE 0 END) as wkdaysinmonth,

(DATEDIFF(dd, startofmonth, today) + 1)
-(DATEDIFF(wk, startofmonth, today) * 2)
-(CASE WHEN DATENAME(dw, startofmonth) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, today) = 'Saturday' THEN 1 ELSE 0 END) as wkdaystodate

from dates
)
SELECT DISTINCT Customers.EmailAddress as email,
o1.YTD
FROM
Customers
INNER JOIN
Orders
ON
Orders.CustomerID= Customers.CustomerID
JOIN
(SELECT
c.EmailAddress,
SUM(Orders.PaymentAmount) AS YTD
FROM
Customers c
JOIN
Orders
ON c.CustomerID=Orders.CustomerID
WHERE
Orders.OrderDate BETWEEN '01/01/2018 00:00' AND GETDATE()
GROUP BY
EmailAddress) AS o1 ON o1.EmailAddress = Customers.EmailAddress
WHERE
Orders.OrderDate >= (GETDATE()-7)









share|improve this question



























    up vote
    1
    down vote

    favorite












    I am trying to add MTD Sales in a SQL Query. I figured out how to do that with JOINS but i want to use a CTE to calculate MTD sales and then use that to calculate projected_sales.Formula for projected sales is (MTD/wkdaysinmonth*wkdaystodate)[which is also stored in CTE Table). Is there a way to make it easy? I wrote the following code;



    Input:



    Email PaymentAmount orderdate
    xyz@gmail.com 10 11/01/2018
    xyz@gmail.com 20 11/09/2018


    sample output:



    EmailAddress MTD Projected_sales
    xyz@gmail.com 30 0.19


    where Projected sales is calculated as number of days passed=7 and total number of business days in november 22. [30/7*22]=0.19 (Present date = 11/09/2018)



    with dates as(
    select dateadd(d,-day(getdate())+1,convert(date,getdate())) as startofmonth,
    dateadd(d,-1,dateadd(m,1,dateadd(d,-day(getdate())+1,convert(date,getdate())))) as endofmonth,
    convert(date,getdate()) as today
    )
    ,daycounts as(
    select dates.*,

    (DATEDIFF(dd, startofmonth, endofmonth) + 1)
    -(DATEDIFF(wk, startofmonth, endofmonth) * 2)
    -(CASE WHEN DATENAME(dw, startofmonth) = 'Sunday' THEN 1 ELSE 0 END)
    -(CASE WHEN DATENAME(dw, endofmonth) = 'Saturday' THEN 1 ELSE 0 END) as wkdaysinmonth,

    (DATEDIFF(dd, startofmonth, today) + 1)
    -(DATEDIFF(wk, startofmonth, today) * 2)
    -(CASE WHEN DATENAME(dw, startofmonth) = 'Sunday' THEN 1 ELSE 0 END)
    -(CASE WHEN DATENAME(dw, today) = 'Saturday' THEN 1 ELSE 0 END) as wkdaystodate

    from dates
    )
    SELECT DISTINCT Customers.EmailAddress as email,
    o1.YTD
    FROM
    Customers
    INNER JOIN
    Orders
    ON
    Orders.CustomerID= Customers.CustomerID
    JOIN
    (SELECT
    c.EmailAddress,
    SUM(Orders.PaymentAmount) AS YTD
    FROM
    Customers c
    JOIN
    Orders
    ON c.CustomerID=Orders.CustomerID
    WHERE
    Orders.OrderDate BETWEEN '01/01/2018 00:00' AND GETDATE()
    GROUP BY
    EmailAddress) AS o1 ON o1.EmailAddress = Customers.EmailAddress
    WHERE
    Orders.OrderDate >= (GETDATE()-7)









    share|improve this question

























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I am trying to add MTD Sales in a SQL Query. I figured out how to do that with JOINS but i want to use a CTE to calculate MTD sales and then use that to calculate projected_sales.Formula for projected sales is (MTD/wkdaysinmonth*wkdaystodate)[which is also stored in CTE Table). Is there a way to make it easy? I wrote the following code;



      Input:



      Email PaymentAmount orderdate
      xyz@gmail.com 10 11/01/2018
      xyz@gmail.com 20 11/09/2018


      sample output:



      EmailAddress MTD Projected_sales
      xyz@gmail.com 30 0.19


      where Projected sales is calculated as number of days passed=7 and total number of business days in november 22. [30/7*22]=0.19 (Present date = 11/09/2018)



      with dates as(
      select dateadd(d,-day(getdate())+1,convert(date,getdate())) as startofmonth,
      dateadd(d,-1,dateadd(m,1,dateadd(d,-day(getdate())+1,convert(date,getdate())))) as endofmonth,
      convert(date,getdate()) as today
      )
      ,daycounts as(
      select dates.*,

      (DATEDIFF(dd, startofmonth, endofmonth) + 1)
      -(DATEDIFF(wk, startofmonth, endofmonth) * 2)
      -(CASE WHEN DATENAME(dw, startofmonth) = 'Sunday' THEN 1 ELSE 0 END)
      -(CASE WHEN DATENAME(dw, endofmonth) = 'Saturday' THEN 1 ELSE 0 END) as wkdaysinmonth,

      (DATEDIFF(dd, startofmonth, today) + 1)
      -(DATEDIFF(wk, startofmonth, today) * 2)
      -(CASE WHEN DATENAME(dw, startofmonth) = 'Sunday' THEN 1 ELSE 0 END)
      -(CASE WHEN DATENAME(dw, today) = 'Saturday' THEN 1 ELSE 0 END) as wkdaystodate

      from dates
      )
      SELECT DISTINCT Customers.EmailAddress as email,
      o1.YTD
      FROM
      Customers
      INNER JOIN
      Orders
      ON
      Orders.CustomerID= Customers.CustomerID
      JOIN
      (SELECT
      c.EmailAddress,
      SUM(Orders.PaymentAmount) AS YTD
      FROM
      Customers c
      JOIN
      Orders
      ON c.CustomerID=Orders.CustomerID
      WHERE
      Orders.OrderDate BETWEEN '01/01/2018 00:00' AND GETDATE()
      GROUP BY
      EmailAddress) AS o1 ON o1.EmailAddress = Customers.EmailAddress
      WHERE
      Orders.OrderDate >= (GETDATE()-7)









      share|improve this question















      I am trying to add MTD Sales in a SQL Query. I figured out how to do that with JOINS but i want to use a CTE to calculate MTD sales and then use that to calculate projected_sales.Formula for projected sales is (MTD/wkdaysinmonth*wkdaystodate)[which is also stored in CTE Table). Is there a way to make it easy? I wrote the following code;



      Input:



      Email PaymentAmount orderdate
      xyz@gmail.com 10 11/01/2018
      xyz@gmail.com 20 11/09/2018


      sample output:



      EmailAddress MTD Projected_sales
      xyz@gmail.com 30 0.19


      where Projected sales is calculated as number of days passed=7 and total number of business days in november 22. [30/7*22]=0.19 (Present date = 11/09/2018)



      with dates as(
      select dateadd(d,-day(getdate())+1,convert(date,getdate())) as startofmonth,
      dateadd(d,-1,dateadd(m,1,dateadd(d,-day(getdate())+1,convert(date,getdate())))) as endofmonth,
      convert(date,getdate()) as today
      )
      ,daycounts as(
      select dates.*,

      (DATEDIFF(dd, startofmonth, endofmonth) + 1)
      -(DATEDIFF(wk, startofmonth, endofmonth) * 2)
      -(CASE WHEN DATENAME(dw, startofmonth) = 'Sunday' THEN 1 ELSE 0 END)
      -(CASE WHEN DATENAME(dw, endofmonth) = 'Saturday' THEN 1 ELSE 0 END) as wkdaysinmonth,

      (DATEDIFF(dd, startofmonth, today) + 1)
      -(DATEDIFF(wk, startofmonth, today) * 2)
      -(CASE WHEN DATENAME(dw, startofmonth) = 'Sunday' THEN 1 ELSE 0 END)
      -(CASE WHEN DATENAME(dw, today) = 'Saturday' THEN 1 ELSE 0 END) as wkdaystodate

      from dates
      )
      SELECT DISTINCT Customers.EmailAddress as email,
      o1.YTD
      FROM
      Customers
      INNER JOIN
      Orders
      ON
      Orders.CustomerID= Customers.CustomerID
      JOIN
      (SELECT
      c.EmailAddress,
      SUM(Orders.PaymentAmount) AS YTD
      FROM
      Customers c
      JOIN
      Orders
      ON c.CustomerID=Orders.CustomerID
      WHERE
      Orders.OrderDate BETWEEN '01/01/2018 00:00' AND GETDATE()
      GROUP BY
      EmailAddress) AS o1 ON o1.EmailAddress = Customers.EmailAddress
      WHERE
      Orders.OrderDate >= (GETDATE()-7)






      sql sql-server sql-server-2008






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited yesterday









      Mohammad Mohabbati

      284211




      284211










      asked yesterday









      garry

      204




      204






















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote













          You can try to use cte recursive create a calendar table for orderdate startDate to endDate.



          Then OUTER JOIN base on calendar table and do condition aggregate function in subquery get workdate.



          ;WITH cte 
          AS (SELECT email,
          Dateadd(day, 1, Eomonth(Min(orderdate), -1)) minDt,
          Dateadd(day, 1, Eomonth(Max(orderdate))) maxDt
          FROM t
          GROUP BY email
          UNION ALL
          SELECT email,
          Dateadd(day, 1, mindt),
          maxdt
          FROM cte
          WHERE Dateadd(day, 1, mindt) < maxdt),
          cte2
          AS (SELECT *,
          Count(CASE
          WHEN Datename(dw, t1.mindt) NOT IN ('Sunday', 'Saturday' )
          THEN
          1
          END) OVER( ORDER BY t1.mindt) workdt
          FROM cte t1)
          SELECT t1.email,
          t2.total,
          Max(diffdt) / ( Max(workdt) * Max(workdtmax) * 1.0 ) Projected_sales
          FROM (SELECT *,
          Max(workdt)
          OVER(
          partition BY email
          ORDER BY workdt DESC) workdtMax,
          Datediff(day, Min(mindt) OVER(partition BY email ORDER BY workdt)
          , Max(mindt) OVER(partition BY email ORDER BY workdt DESC)) + 1 diffdt
          FROM cte2) t1
          LEFT JOIN (SELECT email,
          Sum(paymentamount) total,
          Min(orderdate) minDt,
          Max(orderdate) maxDt
          FROM t
          GROUP BY email) t2
          ON t1.mindt BETWEEN t2.mindt AND t2.maxdt
          AND t1.email = t2.email
          WHERE t2.total IS NOT NULL
          GROUP BY t1.email,
          t2.total


          sqlfiddle



          Reuslt



          email total Projected_sales
          xyz@gmail.com 30 0.19480519480519





          share|improve this answer




















          • @D-Shih...Thanks for getting back..I am getting an error invalid object name t. In actual my emailaddress data is coming from customers table and date and payment amount is coming from orders table and both are related to each other by customerid. How can i use that in your query?
            – garry
            yesterday










          • You can try to let customers instead of T in my query
            – D-Shih
            yesterday










          • @D-Shih..I have changed customers in top t, but in bottom where a left join is used how can join customers and orders table both? as i am getting payment amount from orders table.
            – garry
            22 hours ago

















          up vote
          0
          down vote













          You can generate a "calendar" table that has the weekdays for each day in the month.



          Your calculation for the projected doesn't make sense to me. So, I've also included what I consider to be a better calculation:



          with dates as (
          select distinct dte,
          (case when datename(weekday, dte) not in ('Saturday', 'Sunday') then 1 else 0 end) as num_weekdays,
          dte as month_start
          from t cross apply
          (values (dateadd(day, 1 - day(orderdate), orderdate))) v(dte)
          union all
          select dateadd(day, 1, d.dte),
          (case when datename(weekday, dte) not in ('Saturday', 'Sunday') then 1 else 0 end) + num_weekdays,
          d.month_start
          from dates d
          where dte < dateadd(day, -1, dateadd(month, 1, month_start))
          ),
          d as (
          select d.*, max(num_weekdays) over (partition by month_start) as month_weekdays
          from dates d
          )
          select d.month_start, t.email,
          sum(paymentamount) as mtd,
          sum(paymentamount) * max(month_weekdays) / max(d.num_weekdays) as my_projected,
          sum(paymentamount) * 1.0 / (max(month_weekdays) * max(d.num_weekdays)) as your_projected
          from t join
          d
          on t.orderdate = d.orderdate
          group by d.month_start, t.email;


          Here is a db<>fiddle.






          share|improve this answer




















          • ..Thanks for replying back. I am getting an error invalid object name t. In actual my emailaddress data is coming from customers table and date and payment amount is coming from orders table and both are related to each other by customerid. How can i use that in your query?
            – garry
            yesterday










          • @garry . . . t represents what you call "input" in your question. It is not clear to me how this relates to your much more complicated query.
            – Gordon Linoff
            yesterday










          • so my input is coming from two table customers and orders. how i will use that
            – garry
            yesterday










          • @garry . . . Just add a CTE and call it t. Be sure it is the first CTE defined in the query.
            – Gordon Linoff
            yesterday










          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%2f53237364%2fcalculate-mtd-using-cte-and-projected-sales-in-sql%23new-answer', 'question_page');

          );

          Post as a guest






























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote













          You can try to use cte recursive create a calendar table for orderdate startDate to endDate.



          Then OUTER JOIN base on calendar table and do condition aggregate function in subquery get workdate.



          ;WITH cte 
          AS (SELECT email,
          Dateadd(day, 1, Eomonth(Min(orderdate), -1)) minDt,
          Dateadd(day, 1, Eomonth(Max(orderdate))) maxDt
          FROM t
          GROUP BY email
          UNION ALL
          SELECT email,
          Dateadd(day, 1, mindt),
          maxdt
          FROM cte
          WHERE Dateadd(day, 1, mindt) < maxdt),
          cte2
          AS (SELECT *,
          Count(CASE
          WHEN Datename(dw, t1.mindt) NOT IN ('Sunday', 'Saturday' )
          THEN
          1
          END) OVER( ORDER BY t1.mindt) workdt
          FROM cte t1)
          SELECT t1.email,
          t2.total,
          Max(diffdt) / ( Max(workdt) * Max(workdtmax) * 1.0 ) Projected_sales
          FROM (SELECT *,
          Max(workdt)
          OVER(
          partition BY email
          ORDER BY workdt DESC) workdtMax,
          Datediff(day, Min(mindt) OVER(partition BY email ORDER BY workdt)
          , Max(mindt) OVER(partition BY email ORDER BY workdt DESC)) + 1 diffdt
          FROM cte2) t1
          LEFT JOIN (SELECT email,
          Sum(paymentamount) total,
          Min(orderdate) minDt,
          Max(orderdate) maxDt
          FROM t
          GROUP BY email) t2
          ON t1.mindt BETWEEN t2.mindt AND t2.maxdt
          AND t1.email = t2.email
          WHERE t2.total IS NOT NULL
          GROUP BY t1.email,
          t2.total


          sqlfiddle



          Reuslt



          email total Projected_sales
          xyz@gmail.com 30 0.19480519480519





          share|improve this answer




















          • @D-Shih...Thanks for getting back..I am getting an error invalid object name t. In actual my emailaddress data is coming from customers table and date and payment amount is coming from orders table and both are related to each other by customerid. How can i use that in your query?
            – garry
            yesterday










          • You can try to let customers instead of T in my query
            – D-Shih
            yesterday










          • @D-Shih..I have changed customers in top t, but in bottom where a left join is used how can join customers and orders table both? as i am getting payment amount from orders table.
            – garry
            22 hours ago














          up vote
          1
          down vote













          You can try to use cte recursive create a calendar table for orderdate startDate to endDate.



          Then OUTER JOIN base on calendar table and do condition aggregate function in subquery get workdate.



          ;WITH cte 
          AS (SELECT email,
          Dateadd(day, 1, Eomonth(Min(orderdate), -1)) minDt,
          Dateadd(day, 1, Eomonth(Max(orderdate))) maxDt
          FROM t
          GROUP BY email
          UNION ALL
          SELECT email,
          Dateadd(day, 1, mindt),
          maxdt
          FROM cte
          WHERE Dateadd(day, 1, mindt) < maxdt),
          cte2
          AS (SELECT *,
          Count(CASE
          WHEN Datename(dw, t1.mindt) NOT IN ('Sunday', 'Saturday' )
          THEN
          1
          END) OVER( ORDER BY t1.mindt) workdt
          FROM cte t1)
          SELECT t1.email,
          t2.total,
          Max(diffdt) / ( Max(workdt) * Max(workdtmax) * 1.0 ) Projected_sales
          FROM (SELECT *,
          Max(workdt)
          OVER(
          partition BY email
          ORDER BY workdt DESC) workdtMax,
          Datediff(day, Min(mindt) OVER(partition BY email ORDER BY workdt)
          , Max(mindt) OVER(partition BY email ORDER BY workdt DESC)) + 1 diffdt
          FROM cte2) t1
          LEFT JOIN (SELECT email,
          Sum(paymentamount) total,
          Min(orderdate) minDt,
          Max(orderdate) maxDt
          FROM t
          GROUP BY email) t2
          ON t1.mindt BETWEEN t2.mindt AND t2.maxdt
          AND t1.email = t2.email
          WHERE t2.total IS NOT NULL
          GROUP BY t1.email,
          t2.total


          sqlfiddle



          Reuslt



          email total Projected_sales
          xyz@gmail.com 30 0.19480519480519





          share|improve this answer




















          • @D-Shih...Thanks for getting back..I am getting an error invalid object name t. In actual my emailaddress data is coming from customers table and date and payment amount is coming from orders table and both are related to each other by customerid. How can i use that in your query?
            – garry
            yesterday










          • You can try to let customers instead of T in my query
            – D-Shih
            yesterday










          • @D-Shih..I have changed customers in top t, but in bottom where a left join is used how can join customers and orders table both? as i am getting payment amount from orders table.
            – garry
            22 hours ago












          up vote
          1
          down vote










          up vote
          1
          down vote









          You can try to use cte recursive create a calendar table for orderdate startDate to endDate.



          Then OUTER JOIN base on calendar table and do condition aggregate function in subquery get workdate.



          ;WITH cte 
          AS (SELECT email,
          Dateadd(day, 1, Eomonth(Min(orderdate), -1)) minDt,
          Dateadd(day, 1, Eomonth(Max(orderdate))) maxDt
          FROM t
          GROUP BY email
          UNION ALL
          SELECT email,
          Dateadd(day, 1, mindt),
          maxdt
          FROM cte
          WHERE Dateadd(day, 1, mindt) < maxdt),
          cte2
          AS (SELECT *,
          Count(CASE
          WHEN Datename(dw, t1.mindt) NOT IN ('Sunday', 'Saturday' )
          THEN
          1
          END) OVER( ORDER BY t1.mindt) workdt
          FROM cte t1)
          SELECT t1.email,
          t2.total,
          Max(diffdt) / ( Max(workdt) * Max(workdtmax) * 1.0 ) Projected_sales
          FROM (SELECT *,
          Max(workdt)
          OVER(
          partition BY email
          ORDER BY workdt DESC) workdtMax,
          Datediff(day, Min(mindt) OVER(partition BY email ORDER BY workdt)
          , Max(mindt) OVER(partition BY email ORDER BY workdt DESC)) + 1 diffdt
          FROM cte2) t1
          LEFT JOIN (SELECT email,
          Sum(paymentamount) total,
          Min(orderdate) minDt,
          Max(orderdate) maxDt
          FROM t
          GROUP BY email) t2
          ON t1.mindt BETWEEN t2.mindt AND t2.maxdt
          AND t1.email = t2.email
          WHERE t2.total IS NOT NULL
          GROUP BY t1.email,
          t2.total


          sqlfiddle



          Reuslt



          email total Projected_sales
          xyz@gmail.com 30 0.19480519480519





          share|improve this answer












          You can try to use cte recursive create a calendar table for orderdate startDate to endDate.



          Then OUTER JOIN base on calendar table and do condition aggregate function in subquery get workdate.



          ;WITH cte 
          AS (SELECT email,
          Dateadd(day, 1, Eomonth(Min(orderdate), -1)) minDt,
          Dateadd(day, 1, Eomonth(Max(orderdate))) maxDt
          FROM t
          GROUP BY email
          UNION ALL
          SELECT email,
          Dateadd(day, 1, mindt),
          maxdt
          FROM cte
          WHERE Dateadd(day, 1, mindt) < maxdt),
          cte2
          AS (SELECT *,
          Count(CASE
          WHEN Datename(dw, t1.mindt) NOT IN ('Sunday', 'Saturday' )
          THEN
          1
          END) OVER( ORDER BY t1.mindt) workdt
          FROM cte t1)
          SELECT t1.email,
          t2.total,
          Max(diffdt) / ( Max(workdt) * Max(workdtmax) * 1.0 ) Projected_sales
          FROM (SELECT *,
          Max(workdt)
          OVER(
          partition BY email
          ORDER BY workdt DESC) workdtMax,
          Datediff(day, Min(mindt) OVER(partition BY email ORDER BY workdt)
          , Max(mindt) OVER(partition BY email ORDER BY workdt DESC)) + 1 diffdt
          FROM cte2) t1
          LEFT JOIN (SELECT email,
          Sum(paymentamount) total,
          Min(orderdate) minDt,
          Max(orderdate) maxDt
          FROM t
          GROUP BY email) t2
          ON t1.mindt BETWEEN t2.mindt AND t2.maxdt
          AND t1.email = t2.email
          WHERE t2.total IS NOT NULL
          GROUP BY t1.email,
          t2.total


          sqlfiddle



          Reuslt



          email total Projected_sales
          xyz@gmail.com 30 0.19480519480519






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered yesterday









          D-Shih

          23.5k61331




          23.5k61331











          • @D-Shih...Thanks for getting back..I am getting an error invalid object name t. In actual my emailaddress data is coming from customers table and date and payment amount is coming from orders table and both are related to each other by customerid. How can i use that in your query?
            – garry
            yesterday










          • You can try to let customers instead of T in my query
            – D-Shih
            yesterday










          • @D-Shih..I have changed customers in top t, but in bottom where a left join is used how can join customers and orders table both? as i am getting payment amount from orders table.
            – garry
            22 hours ago
















          • @D-Shih...Thanks for getting back..I am getting an error invalid object name t. In actual my emailaddress data is coming from customers table and date and payment amount is coming from orders table and both are related to each other by customerid. How can i use that in your query?
            – garry
            yesterday










          • You can try to let customers instead of T in my query
            – D-Shih
            yesterday










          • @D-Shih..I have changed customers in top t, but in bottom where a left join is used how can join customers and orders table both? as i am getting payment amount from orders table.
            – garry
            22 hours ago















          @D-Shih...Thanks for getting back..I am getting an error invalid object name t. In actual my emailaddress data is coming from customers table and date and payment amount is coming from orders table and both are related to each other by customerid. How can i use that in your query?
          – garry
          yesterday




          @D-Shih...Thanks for getting back..I am getting an error invalid object name t. In actual my emailaddress data is coming from customers table and date and payment amount is coming from orders table and both are related to each other by customerid. How can i use that in your query?
          – garry
          yesterday












          You can try to let customers instead of T in my query
          – D-Shih
          yesterday




          You can try to let customers instead of T in my query
          – D-Shih
          yesterday












          @D-Shih..I have changed customers in top t, but in bottom where a left join is used how can join customers and orders table both? as i am getting payment amount from orders table.
          – garry
          22 hours ago




          @D-Shih..I have changed customers in top t, but in bottom where a left join is used how can join customers and orders table both? as i am getting payment amount from orders table.
          – garry
          22 hours ago












          up vote
          0
          down vote













          You can generate a "calendar" table that has the weekdays for each day in the month.



          Your calculation for the projected doesn't make sense to me. So, I've also included what I consider to be a better calculation:



          with dates as (
          select distinct dte,
          (case when datename(weekday, dte) not in ('Saturday', 'Sunday') then 1 else 0 end) as num_weekdays,
          dte as month_start
          from t cross apply
          (values (dateadd(day, 1 - day(orderdate), orderdate))) v(dte)
          union all
          select dateadd(day, 1, d.dte),
          (case when datename(weekday, dte) not in ('Saturday', 'Sunday') then 1 else 0 end) + num_weekdays,
          d.month_start
          from dates d
          where dte < dateadd(day, -1, dateadd(month, 1, month_start))
          ),
          d as (
          select d.*, max(num_weekdays) over (partition by month_start) as month_weekdays
          from dates d
          )
          select d.month_start, t.email,
          sum(paymentamount) as mtd,
          sum(paymentamount) * max(month_weekdays) / max(d.num_weekdays) as my_projected,
          sum(paymentamount) * 1.0 / (max(month_weekdays) * max(d.num_weekdays)) as your_projected
          from t join
          d
          on t.orderdate = d.orderdate
          group by d.month_start, t.email;


          Here is a db<>fiddle.






          share|improve this answer




















          • ..Thanks for replying back. I am getting an error invalid object name t. In actual my emailaddress data is coming from customers table and date and payment amount is coming from orders table and both are related to each other by customerid. How can i use that in your query?
            – garry
            yesterday










          • @garry . . . t represents what you call "input" in your question. It is not clear to me how this relates to your much more complicated query.
            – Gordon Linoff
            yesterday










          • so my input is coming from two table customers and orders. how i will use that
            – garry
            yesterday










          • @garry . . . Just add a CTE and call it t. Be sure it is the first CTE defined in the query.
            – Gordon Linoff
            yesterday














          up vote
          0
          down vote













          You can generate a "calendar" table that has the weekdays for each day in the month.



          Your calculation for the projected doesn't make sense to me. So, I've also included what I consider to be a better calculation:



          with dates as (
          select distinct dte,
          (case when datename(weekday, dte) not in ('Saturday', 'Sunday') then 1 else 0 end) as num_weekdays,
          dte as month_start
          from t cross apply
          (values (dateadd(day, 1 - day(orderdate), orderdate))) v(dte)
          union all
          select dateadd(day, 1, d.dte),
          (case when datename(weekday, dte) not in ('Saturday', 'Sunday') then 1 else 0 end) + num_weekdays,
          d.month_start
          from dates d
          where dte < dateadd(day, -1, dateadd(month, 1, month_start))
          ),
          d as (
          select d.*, max(num_weekdays) over (partition by month_start) as month_weekdays
          from dates d
          )
          select d.month_start, t.email,
          sum(paymentamount) as mtd,
          sum(paymentamount) * max(month_weekdays) / max(d.num_weekdays) as my_projected,
          sum(paymentamount) * 1.0 / (max(month_weekdays) * max(d.num_weekdays)) as your_projected
          from t join
          d
          on t.orderdate = d.orderdate
          group by d.month_start, t.email;


          Here is a db<>fiddle.






          share|improve this answer




















          • ..Thanks for replying back. I am getting an error invalid object name t. In actual my emailaddress data is coming from customers table and date and payment amount is coming from orders table and both are related to each other by customerid. How can i use that in your query?
            – garry
            yesterday










          • @garry . . . t represents what you call "input" in your question. It is not clear to me how this relates to your much more complicated query.
            – Gordon Linoff
            yesterday










          • so my input is coming from two table customers and orders. how i will use that
            – garry
            yesterday










          • @garry . . . Just add a CTE and call it t. Be sure it is the first CTE defined in the query.
            – Gordon Linoff
            yesterday












          up vote
          0
          down vote










          up vote
          0
          down vote









          You can generate a "calendar" table that has the weekdays for each day in the month.



          Your calculation for the projected doesn't make sense to me. So, I've also included what I consider to be a better calculation:



          with dates as (
          select distinct dte,
          (case when datename(weekday, dte) not in ('Saturday', 'Sunday') then 1 else 0 end) as num_weekdays,
          dte as month_start
          from t cross apply
          (values (dateadd(day, 1 - day(orderdate), orderdate))) v(dte)
          union all
          select dateadd(day, 1, d.dte),
          (case when datename(weekday, dte) not in ('Saturday', 'Sunday') then 1 else 0 end) + num_weekdays,
          d.month_start
          from dates d
          where dte < dateadd(day, -1, dateadd(month, 1, month_start))
          ),
          d as (
          select d.*, max(num_weekdays) over (partition by month_start) as month_weekdays
          from dates d
          )
          select d.month_start, t.email,
          sum(paymentamount) as mtd,
          sum(paymentamount) * max(month_weekdays) / max(d.num_weekdays) as my_projected,
          sum(paymentamount) * 1.0 / (max(month_weekdays) * max(d.num_weekdays)) as your_projected
          from t join
          d
          on t.orderdate = d.orderdate
          group by d.month_start, t.email;


          Here is a db<>fiddle.






          share|improve this answer












          You can generate a "calendar" table that has the weekdays for each day in the month.



          Your calculation for the projected doesn't make sense to me. So, I've also included what I consider to be a better calculation:



          with dates as (
          select distinct dte,
          (case when datename(weekday, dte) not in ('Saturday', 'Sunday') then 1 else 0 end) as num_weekdays,
          dte as month_start
          from t cross apply
          (values (dateadd(day, 1 - day(orderdate), orderdate))) v(dte)
          union all
          select dateadd(day, 1, d.dte),
          (case when datename(weekday, dte) not in ('Saturday', 'Sunday') then 1 else 0 end) + num_weekdays,
          d.month_start
          from dates d
          where dte < dateadd(day, -1, dateadd(month, 1, month_start))
          ),
          d as (
          select d.*, max(num_weekdays) over (partition by month_start) as month_weekdays
          from dates d
          )
          select d.month_start, t.email,
          sum(paymentamount) as mtd,
          sum(paymentamount) * max(month_weekdays) / max(d.num_weekdays) as my_projected,
          sum(paymentamount) * 1.0 / (max(month_weekdays) * max(d.num_weekdays)) as your_projected
          from t join
          d
          on t.orderdate = d.orderdate
          group by d.month_start, t.email;


          Here is a db<>fiddle.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered yesterday









          Gordon Linoff

          741k32285389




          741k32285389











          • ..Thanks for replying back. I am getting an error invalid object name t. In actual my emailaddress data is coming from customers table and date and payment amount is coming from orders table and both are related to each other by customerid. How can i use that in your query?
            – garry
            yesterday










          • @garry . . . t represents what you call "input" in your question. It is not clear to me how this relates to your much more complicated query.
            – Gordon Linoff
            yesterday










          • so my input is coming from two table customers and orders. how i will use that
            – garry
            yesterday










          • @garry . . . Just add a CTE and call it t. Be sure it is the first CTE defined in the query.
            – Gordon Linoff
            yesterday
















          • ..Thanks for replying back. I am getting an error invalid object name t. In actual my emailaddress data is coming from customers table and date and payment amount is coming from orders table and both are related to each other by customerid. How can i use that in your query?
            – garry
            yesterday










          • @garry . . . t represents what you call "input" in your question. It is not clear to me how this relates to your much more complicated query.
            – Gordon Linoff
            yesterday










          • so my input is coming from two table customers and orders. how i will use that
            – garry
            yesterday










          • @garry . . . Just add a CTE and call it t. Be sure it is the first CTE defined in the query.
            – Gordon Linoff
            yesterday















          ..Thanks for replying back. I am getting an error invalid object name t. In actual my emailaddress data is coming from customers table and date and payment amount is coming from orders table and both are related to each other by customerid. How can i use that in your query?
          – garry
          yesterday




          ..Thanks for replying back. I am getting an error invalid object name t. In actual my emailaddress data is coming from customers table and date and payment amount is coming from orders table and both are related to each other by customerid. How can i use that in your query?
          – garry
          yesterday












          @garry . . . t represents what you call "input" in your question. It is not clear to me how this relates to your much more complicated query.
          – Gordon Linoff
          yesterday




          @garry . . . t represents what you call "input" in your question. It is not clear to me how this relates to your much more complicated query.
          – Gordon Linoff
          yesterday












          so my input is coming from two table customers and orders. how i will use that
          – garry
          yesterday




          so my input is coming from two table customers and orders. how i will use that
          – garry
          yesterday












          @garry . . . Just add a CTE and call it t. Be sure it is the first CTE defined in the query.
          – Gordon Linoff
          yesterday




          @garry . . . Just add a CTE and call it t. Be sure it is the first CTE defined in the query.
          – Gordon Linoff
          yesterday

















           

          draft saved


          draft discarded















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237364%2fcalculate-mtd-using-cte-and-projected-sales-in-sql%23new-answer', 'question_page');

          );

          Post as a guest














































































          Popular posts from this blog

          Top Tejano songwriter Luis Silva dead of heart attack at 64

          政党

          天津地下鉄3号線