Rachel
Rachel

Reputation: 1

How to Show Previous Year on Dynamic Date

I have a database that has customer, product, date and volume/revenue data. I'd like to create two NEW columns to show the previous year volume and revenue based on the date/customer/product.

I've tried unioning two views, one that has dates (unchanged) and a second view that creates a CTE where I select the dates minus one year with another select statement off of that where VOL and REV are renamed VOL_PY and REV_PY but the data is incomplete. Basically what's happening is the PY data is only pulling volume and revenue if there is data in the prior year (for example if a customer didn't sell a product in 2021 but DID in 2020, it wouldn't pull for the VOL_PY for 2020 - because it didn't sell in 2021). How do I get my code to include matches in dates but also the instances where there isn't data in the "current" year?

Here's what I'm going for: [EXAMPLE DATA WITH NEW COLUMNS]

1

CURRENT YEAR VIEW:

   SELECT
   CUSTOMER
  ,PRODUCT
  ,DATE
  ,VOL
  ,REV
  ,0 AS VOL_HL_PY
  ,0 AS REV_DOLS_PY
  ,DATEADD(YEAR, -1, DATE) AS DATE_PY FROM dbo.vwReporting

PREVIOUS YEAR VIEW:

WITH CTE_PYFIGURES 
     ([AUTONUMBER]
      ,CUSTOMER
      ,PRODUCT
      ,DATE
      ,VOL
      ,REV
      ,DATE_PY
      ) AS 

(
SELECT b.*
     , DATEADD(YEAR, 1, DATE) AS DATE_PY
FROM dbo.basetable b
)

SELECT  
       v.CUSTOMER
      ,v.PRODUCT
      ,v.DATE
      ,0 AS v.VOL
      ,0 AS v.REV
      ,CTE.VOL_HL AS VOL_HL_PY
      ,CTE.REV_DOLS AS REV_DOLS_PY
      ,DATEADD(YEAR,-1,CTE.PERIOD_DATE_PY) AS PERIOD_DATE_PY
FROM dbo.vwReporting AS v
FULL OUTER JOIN CTE_PYFIGURES AS CTE ON CTE.CUSTOMER=V.CUSTOMER AND CTE.PRODUCT=V.PRODCUT AND CTE.DATE_PY=V.DATE 

Upvotes: 0

Views: 1017

Answers (1)

astentx
astentx

Reputation: 6751

You need to offset your current year's data to one year forward and then union it with the current data, placing zeroes for "other" measures (VOL and REV for previous year and VOL_PY and REV_PY for current year). Then do aggregation. This way you'll have all the dimensions' values that were in current or previous year.

with a as (
  select
    CUSTOMER
    , PRODUCT
    , [DATE]
    , VOL
    , REV
    , 0 as vol_py
    , 0 as rev_py
  from dbo.vwReporting

  union all

  select
    CUSTOMER
    , PRODUCT
    , dateadd(year, 1, [DATE]) as [DATE]
    , 0 as VOL
    , 0 as REV
    , vol as vol_py
    , rev as rev_py
  from dbo.vwReporting
)
select
    CUSTOMER
    , PRODUCT
    , [DATE]
    , VOL
    , sum(vol) as vol
    , sum(rev) as rev
    , sum(vol_py) as vol_py
    , sum(rev_py) as rev_py
from a
group by
    CUSTOMER
    , PRODUCT
    , [DATE]
    , VOL

Upvotes: 1

Related Questions