【问题标题】:How to match up dates on 2 different tables and join to an ID table?如何匹配 2 个不同表上的日期并加入 ID 表?
【发布时间】:2019-06-13 05:11:34
【问题描述】:

我有一张表,里面有产品 ID 及其属性。我想加入来自 2 个不同表的销售数据和收据数据以及每个 id 和 date 组合的不同行。所以我希望输出看起来像这样:

我尝试将产品 ID 表和销售表加入收据表,但我不确定如何从销售和收据表中获取日期以匹配。不知道如何解决这个问题。谢谢!

【问题讨论】:

标签: mysql sql teradata


【解决方案1】:

计算每个表的计数并使用 UNION ALL 组合它们

select
   product_id
  ,sales_date
   -- combine the counts from both tables
  ,sum(sales_count)
  ,sum(receipt_count)
from
 (
   -- get the counts for the sales table
   select
      product_id
     ,sales_date
     ,count(*) as sales_count
      -- UNION needs the same number of columns in both Select -> adding a dummy column
      -- 1st Select determines the datatype
     ,cast(0 as int) as receipt_count
   from sales 
   group by product_id, sales_date

   UNION ALL

   -- get the counts for the receipts table
   select
      product_id
     ,receipt_date
     ,0
     ,count(*) 
   from receipts 
   group by product_id, receipt_date
 ) as dt
group by product_id, receipt_date

【讨论】:

  • 感谢这工作!我现在数据太多了哈哈
【解决方案2】:
select p.product_id, s.sales_date, s.sales_count, r.receipt_count
from
  products p,
  (select count(*) sales_count, sales_date, product_id from sales group by 2,3) s
  (select count(*) receipt_count, receipt_date, product_id from receipts group by 2,3) r
where 
  p.product_id = s.product_id
  and p.product_id = r.product_id
  and s.sales_date=r.receipt_date
;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    相关资源
    最近更新 更多