首页 文章

并行日期销售SQL视图

提问于
浏览
1

我有一个挑战,我似乎无法自己解决,现在需要帮助!

我要求通过SQL显示并行年份日期销售,我的意思是,如果今天(2015年8月20日)客户A购买了 Value 500的产品,我想知道客户A在去年同一天花了多少钱(所以20/08/2014) .

这是SQL fiddle,其中我 Build 在顶部 . 我还在右侧留下了一个查询,我在20150820为6500的事实表中为安东尼奥创造了另外一个记录 . 所以我想要的是拥有在20140820上卖出的3500(这是并行年份日期20150820)在ParallelSales列下(此时显示为NULL) .

如果我在视图中不包含ProductKey并且只有CustomerKey(see this fiddle),那么它就像一个魅力 . 但是,只要我添加产品密钥,因为过去发生的CustomerKey-ProductKey没有完全匹配,我认为原因是这样 .

我想要做的是然后使用视图并连接DimCustomer和DimProduct并以两种方式运行查询,即:

问题1:客户A今天与去年相比多少钱?问题2:我们今天销售的产品A与去年相比有多少?

目前,我需要有2个视图 - 一个在CustomerKey视图中连接两个子查询,另一个在ProductKey上(显然是日期) .

我知道要问很多,但我确实需要这个工作,非常感谢你的帮助!谢谢 :)

1 回答

  • 2

    适用于不同年份的客户销售 .

    SQL Fiddle Demo

    SELECT DimCustomer.CustomerName,
           VW_Current.Saledate,
           VW_Current.ParallelDate,
           VW_Current.CurrentSales,
           VW_Previous.CurrentSales as ParallelSale
    
    FROM   DimCustomer 
           INNER JOIN VW_ParallelSales VW_Current
               ON DimCustomer.CustomerKey = VW_Current.CustomerKey
           LEFT JOIN VW_ParallelSales VW_Previous
               ON VW_Current.ParallelDate = VW_Previous.Saledate
              AND DimCustomer.CustomerKey = VW_Previous.CustomerKey
    ORDER BY 1, 2
    

    对于productkey

    SQL Fiddle Demo

    With sales as (
        SELECT 
               DimProduct.ProductKey,
               DimProduct.ProductName,
               VW_ParallelSales.Saledate,
               VW_ParallelSales.ParallelDate,
               VW_ParallelSales.CurrentSales,
               VW_ParallelSales.ParallelSales
        FROM   DimProduct INNER JOIN VW_ParallelSales ON DimProduct.ProductKey = 
               VW_ParallelSales.ProductKey
    )
    SELECT 
       s_recent.ProductName,
       s_recent.Saledate ThisYear,
       s_old.Saledate PreviousYear,
       s_recent.CurrentSales CurrentSales,
       s_old.CurrentSales ParallelSales
    FROM 
        SALES s_recent 
        left outer join SALES s_old 
            on s_recent.saledate = s_old.saledate + 10000
           and s_recent.ProductKey = s_old.ProductKey
    

相关问题