在同一日期结构中显示具有不同时间线的两个字段

Showing Two Fields With Different Timeline in the Same Date Structure

在我公司目前从事的项目中,我想在 SQL / Tableau / BigQuery

上显示与销售相关的 KPI 以及客户评分指标

主键是两个表中的订单id。但是,订单日期和我们衡量客户评分的日期可能不同。例如,2020 年 2 月发布的订单的销售信息将在 2020 年 2 月汇总,但是如果客户调查是在 2020 年 3 月进行的,则客户评分指标必须在 2020 年 3 月汇总。我想在关系型数据库中实现是as follows:

销售额:

Order ID Order Date(m/d/yyyy) Sales ($)
1000 1/1/2021 1000
1001 2/1/2021 2000
1002 3/1/2021 1500
1003 4/1/2021 1700
1004 5/1/2021 1800
1005 6/1/2021 900
1006 7/1/2021 1600
1007 8/1/2021 1900

客户评分Table:

Order ID Customer Survey Date(m/d/yyyy) Customer Score
1000 3/1/2021 8
1001 3/1/2021 7
1002 4/1/2021 3
1003 6/1/2021 6
1004 6/1/2021 5
1005 7/1/2021 3
1006 9/1/2021 1
1007 8/1/2021 7

预期输出:

KPI Jan-21 Feb-21 Mar-21 Apr-21 May-21 June-21 July-21 Aug-21 Sep-21
Sales($) 1000 2000 1500 1700 1800 900 1600 1900
AVG Customer Score 7.5 3 5.5 3 7 1

我找不到办法做到这一点,因为订单日期和调查日期 may/may 不一样。

对于示例数据和预期输出,click here

我想你要做的是在加入之前先将你的结果汇总到月份 (KPI),而不是在 ORDER_ID

加入

例如:

with order_month as (
  select date_trunc(order_date, MONTH) as KPI, sum(sales) as sales
  from `testing.sales`
  group by 1
  ),
  customer_score_month as (
  select date_trunc(customer_survey_date, MONTH) as KPI, avg(customer_score) as avg_customer_score
  from `testing.customer_score`
  group by 1
  )
  select coalesce(order_month.KPI,customer_score_month.KPI) as KPI, sales, avg_customer_score 
  from order_month
  full outer join customer_score_month
  on order_month.KPI = customer_score_month.KPI
  order by 1 asc

在这里,我们根据订单日期汇总每个月的总销售额,然后我们根据提交评分的日期汇总每个月的平均客户评分。现在我们可以在月值上加入这两个。

这导致 table 像这样:

KPI sales avg_customer_score
2021-01-01 1000 null
2021-02-01 2000 null
2021-03-01 1500 7.5
2021-04-01 1700 3.0
2021-05-01 1800 null
2021-06-01 900 5.5
2021-07-01 1600 3.0
2021-08-01 1900 7.0
2021-09-01 null 1.0

您可以在 Tableau 中转换此 table 的结果,或利用案例语句将每个月提取到其自己的列中 - 如果有帮助,我可以详细说明