首页 > 解决方案 > 如何将 Store_ID 的所有值拉入我的雪花查询?

问题描述

我在下面有一个查询,我试图获取所有的 week_id、upc_id 和 upc_dsc,即使它们没有 net_amt 或 item_qty。我已成功拉入所有商店,但我还想为这些商店显示 upc 和周 ID,以便他们可以查看 upc 是否有 0 销售。我尝试在 s 表的右连接下对我的日期表进行右连接以及对 upc 表进行右连接,但是它弄乱了我的数据并且没有拉入我需要的列。有谁知道如何解决这一问题?

谢谢

  select 
   a.week_id
  , s.district_cd
  , s.store_id
  , a.upc_id
  , a.upc_dsc
  , sum(a.net_amt) as current_week_sales
  , sum(t.net_amt) as last_week_sales
  , sum(a.item_qty) as current_week_units
  , sum(t.item_qty) as last_week_units

  from (
  
select 
 week_id
, district_cd
, str.store_id
, txn.upc_id
, upc_dsc
, dense_rank() over (order by week_id) as rank   
, sum(txn.net_amt) as net_amt
, sum(txn.item_qty) as item_qty

from dw_dss.txn_facts  txn

left join dw_dss.lu_store_finance_om  STR  
on str.store_id = txn.store_id
 join dw_dss.lu_upc upc
on upc.upc_id = txn.upc_id
 join lu_day_merge day
on day.d_date = txn.txn_dte
where district_cd in (72,73)
and txn.upc_id in (27610100000
,27610200000
,27610300000
,27610400000
)
and division_id = 19
and txn_dte between '2021-07-25' and current_date - 1
group by 1,2,3,4,5

) a

left join temp_tables.ab_week_ago t
on t.rank = a.rank and a.store_id = t.store_id and a.upc_id = t.upc_id

right join dw_dss.lu_store_finance_om s 
on s.store_id = a.store_id

where s.division_id = 19
and s.district_cd in (72,73)

group by 1,2,3,4,5
    
   

标签: sqljoinsnowflake-cloud-data-platform

解决方案


如前一条评论所述,该示例太长而无法调试,尤其是因为未提供源表。

但是,作为一般规则,在为缺少的维度添加零时,我遵循以下步骤:

  1. 构建主查询,这是提取所需数据的所有复杂性的查询 - 只是可用数据,没有丢失维度;测试此查询以确保它给出正确的结果,并按每个维度正确聚合
  2. 然后将此查询用作 WITH 语句中的 CTE,对于此查询,您可以右连接要为其添加零值的所有维度以缺失数据
  3. 请务必仔细检查维度上的过滤,以确保您不会在 WHERE 条件中过滤太多,例如,而不是在最终查询中使用 WHERE 进行过滤,例如您的示例:
right join dw_dss.lu_store_finance_om s 
on s.store_id = a.store_id

where s.division_id = 19
and s.district_cd in (72,73)

我可能宁愿在子查询中过滤维度本身:

right join (select store_id from dw_dss.lu_store_finance_om 
            where s.division_id = 19 and s.district_cd in (72,73)) s 
on s.store_id = a.store_id

推荐阅读