我有一张充满产品ID及其属性的表格。我想将来自2个不同表的销售数据和收据数据以及每个id和日期组合的不同行连接起来。所以我希望输出看起来像这样:
我尝试将产品ID表和销售表加入收据表,但是我不确定如何从销售和收据表中获取日期以进行匹配。不知道如何解决这个问题。谢谢!
答案 0 :(得分:0)
计算每个表的计数,并使用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
答案 1 :(得分:-1)
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
;