我希望我可以更改架构,但我与之相关,假设我有以下表格
JanDataTable
FebDataTable
MarDataTable
ProductsTable
前三个表格中有列ID和已售出金额。产品表有ID和产品名称。
我需要以某种方式连接这些表以获得以下输出
ID | Product Name | Amount Sold | Month
01 | TV 1 | 23 | 1 <- JanDataTable
02 | TV 2 | 43 | 2 <- FebDataTable
03 | Toaster 1 | 72 | 3 <- MarDataTable
ID是产品ID。
只是一个查询吗?
答案 0 :(得分:0)
这个怎么样?
使用LEFT JOIN
执行此操作。
select
p.id as ID, p.`Product Name`,
coalesce(jan.`Amount Sold`,0) + coalesce(feb.`Amount Sold`,0) + coalesce(mar.`Amount Sold`,0) as `Amount Sold`,
case when p.id = '01' then 1
when p.id = '02' then 2
when p.id = '03' thwn 3
end as Month
from ProductsTable as p
LEFT JOIN JanDataTable as jan ON p.id = jan.id
LEFT JOIN FebDataTable as feb ON p.id = feb.id
LEFT JOIN MarDataTable as mar ON p.id = mar.id
答案 1 :(得分:0)
select p.product_part,s.*
from
(
select d.*, 1 as Month from jandatatable d
union
select d.*, 2 as Month from febdatatable d
union
select d.*, 3 as Month from mardatatable d
) s
join product p on s.Product_id = p.product_id
order by s.month, p.product_id;