Calculate MTD using CTE and Projected Sales in SQL










1














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




























    1














    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


























      1












      1








      1







      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 Nov 10 '18 at 12:50









      Mohammad Mohabbati

      487315




      487315










      asked Nov 10 '18 at 8:43









      garry

      224




      224






















          2 Answers
          2






          active

          oldest

          votes


















          1














          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
            Nov 10 '18 at 19:14










          • You can try to let customers instead of T in my query
            – D-Shih
            Nov 10 '18 at 21:50










          • @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
            Nov 11 '18 at 5:16


















          0














          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
            Nov 10 '18 at 19:04










          • @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
            Nov 10 '18 at 19:56










          • so my input is coming from two table customers and orders. how i will use that
            – garry
            Nov 10 '18 at 19:59










          • @garry . . . Just add a CTE and call it t. Be sure it is the first CTE defined in the query.
            – Gordon Linoff
            Nov 10 '18 at 20:01










          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%2f53237364%2fcalculate-mtd-using-cte-and-projected-sales-in-sql%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









          1














          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
            Nov 10 '18 at 19:14










          • You can try to let customers instead of T in my query
            – D-Shih
            Nov 10 '18 at 21:50










          • @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
            Nov 11 '18 at 5:16















          1














          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
            Nov 10 '18 at 19:14










          • You can try to let customers instead of T in my query
            – D-Shih
            Nov 10 '18 at 21:50










          • @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
            Nov 11 '18 at 5:16













          1












          1








          1






          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 Nov 10 '18 at 10:12









          D-Shih

          25.4k61531




          25.4k61531











          • @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
            Nov 10 '18 at 19:14










          • You can try to let customers instead of T in my query
            – D-Shih
            Nov 10 '18 at 21:50










          • @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
            Nov 11 '18 at 5:16
















          • @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
            Nov 10 '18 at 19:14










          • You can try to let customers instead of T in my query
            – D-Shih
            Nov 10 '18 at 21:50










          • @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
            Nov 11 '18 at 5:16















          @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
          Nov 10 '18 at 19:14




          @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
          Nov 10 '18 at 19:14












          You can try to let customers instead of T in my query
          – D-Shih
          Nov 10 '18 at 21:50




          You can try to let customers instead of T in my query
          – D-Shih
          Nov 10 '18 at 21:50












          @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
          Nov 11 '18 at 5:16




          @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
          Nov 11 '18 at 5:16













          0














          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
            Nov 10 '18 at 19:04










          • @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
            Nov 10 '18 at 19:56










          • so my input is coming from two table customers and orders. how i will use that
            – garry
            Nov 10 '18 at 19:59










          • @garry . . . Just add a CTE and call it t. Be sure it is the first CTE defined in the query.
            – Gordon Linoff
            Nov 10 '18 at 20:01















          0














          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
            Nov 10 '18 at 19:04










          • @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
            Nov 10 '18 at 19:56










          • so my input is coming from two table customers and orders. how i will use that
            – garry
            Nov 10 '18 at 19:59










          • @garry . . . Just add a CTE and call it t. Be sure it is the first CTE defined in the query.
            – Gordon Linoff
            Nov 10 '18 at 20:01













          0












          0








          0






          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 Nov 10 '18 at 12:22









          Gordon Linoff

          760k35294399




          760k35294399











          • ..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
            Nov 10 '18 at 19:04










          • @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
            Nov 10 '18 at 19:56










          • so my input is coming from two table customers and orders. how i will use that
            – garry
            Nov 10 '18 at 19:59










          • @garry . . . Just add a CTE and call it t. Be sure it is the first CTE defined in the query.
            – Gordon Linoff
            Nov 10 '18 at 20:01
















          • ..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
            Nov 10 '18 at 19:04










          • @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
            Nov 10 '18 at 19:56










          • so my input is coming from two table customers and orders. how i will use that
            – garry
            Nov 10 '18 at 19:59










          • @garry . . . Just add a CTE and call it t. Be sure it is the first CTE defined in the query.
            – Gordon Linoff
            Nov 10 '18 at 20:01















          ..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
          Nov 10 '18 at 19:04




          ..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
          Nov 10 '18 at 19:04












          @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
          Nov 10 '18 at 19:56




          @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
          Nov 10 '18 at 19:56












          so my input is coming from two table customers and orders. how i will use that
          – garry
          Nov 10 '18 at 19:59




          so my input is coming from two table customers and orders. how i will use that
          – garry
          Nov 10 '18 at 19:59












          @garry . . . Just add a CTE and call it t. Be sure it is the first CTE defined in the query.
          – Gordon Linoff
          Nov 10 '18 at 20:01




          @garry . . . Just add a CTE and call it t. Be sure it is the first CTE defined in the query.
          – Gordon Linoff
          Nov 10 '18 at 20:01

















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f53237364%2fcalculate-mtd-using-cte-and-projected-sales-in-sql%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

          𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

          Crossroads (UK TV series)

          ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế