Forum Discussion

EricB10's avatar
EricB10
Cloud Apps
03-04-2022
Solved

How to create Custom Columns: ThisWeek, ThisWeekPrevYear?

Hi, I am trying to create two boolean Custom Columns in my DimDate table to flag data in the current week, and data in the same week, previous year.  This type of flag is easy to create for a monthl...
  • EricB10's avatar
    04-02-2022

    If anyone is interested, I did eventually find a solution!  This leverages a Common Table Expression in Snowflake, so I don't believe this approach would be possible using only Sisense's data modeling tools.

    Note: in addition to WTD and WTD_PREV_YR, this also contains code to create flags for MTD, MTD_PREV_YR, YTD, YTD_PREV_YR.

    create or replace view DIM_DATE_NEW as (
        with comparison_date as (
            select
                case
                    when weekofyear(current_date()) = 53
                    then 52
                    else weekofyear(current_date())
                end as comp_week
                , date as comp_date
                from <TABLE>
                where year(comp_date) = year(current_date()) - 1
                and weekofyear(comp_date) = comp_week
                and dayofweek(comp_date) = dayofweek(current_date())
        )
        select distinct
            d.date
            , case
                when weekofyear(date) = weekofyear(current_date())
                and date - current_date() <= 0
                and date - current_date() >= -6
                then 1
                else 0
            end as WTD
            , case
                when weekofyear(date) = weekofyear(c.comp_date)
                and date - c.comp_date <= 0
                and date - c.comp_date >= -6
                then 1
                else 0
            end as WTD_PREV_YR
            , CASE
                WHEN MONTH(DATE) = MONTH(CURRENT_DATE())
                AND DAYOFYEAR(DATE) <= DAYOFYEAR(CURRENT_DATE())
                AND YEAR(DATE) = YEAR(CURRENT_DATE())
                THEN 1
                ELSE 0
            END AS MTD
            , CASE
                WHEN MONTH(DATE) = MONTH(CURRENT_DATE())
                AND DAYOFYEAR(DATE) <= DAYOFYEAR(CURRENT_DATE())
                AND YEAR(DATE) = YEAR(CURRENT_DATE()) - 1
                THEN 1
                ELSE 0
            END AS MTD_PREV_YR
            , CASE
                WHEN DAYOFYEAR(DATE) <= DAYOFYEAR(CURRENT_DATE())
                AND YEAR(DATE) = YEAR(CURRENT_DATE())
                THEN 1
                ELSE 0
            END AS YTD
            , CASE
                WHEN DAYOFYEAR(DATE) <= DAYOFYEAR(CURRENT_DATE())
                AND YEAR(DATE) = YEAR(CURRENT_DATE()) - 1
                THEN 1
                ELSE 0
            END AS YTD_PREV_YR
        from <TABLE> as d
        join comparison_date as c on 1=1
        order by date desc
    );