sql - 如何将 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
解决方案
如前一条评论所述,该示例太长而无法调试,尤其是因为未提供源表。
但是,作为一般规则,在为缺少的维度添加零时,我遵循以下步骤:
- 构建主查询,这是提取所需数据的所有复杂性的查询 - 只是可用数据,没有丢失维度;测试此查询以确保它给出正确的结果,并按每个维度正确聚合
- 然后将此查询用作 WITH 语句中的 CTE,对于此查询,您可以右连接要为其添加零值的所有维度以缺失数据
- 请务必仔细检查维度上的过滤,以确保您不会在 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
推荐阅读
- amazon-qldb - 在 QLDB 中查找已删除数据的历史记录
- python - 如何在列操作中找到字符串模式?
- php - 未定义变量:提交表单时的 conn
- r - 在平衡数据框中创建一个变量,该变量是另一列的转置
- php - 修复 CSV 标头的数组键
- angular - Angular 8:PatchValue 不能与 ChangeDetector 和 UpdateValue 一起使用
- machine-learning - Rapid Miner 中的 k-means 质心图实际上是什么意思(用外行的话来说)?
- nsis - 模拟标准 Windows 弹出消息 哔声
- c++ - boost 信号和槽不在不同的线程中工作(使用 boost::asio::io_service)
- javascript - 使用 Firebase 自动注销用户