SQL查询以创建代表历史的结果

时间:2019-02-19 18:50:12

标签: sql

想象一下,如果我有一个带有“产品”的表格,而每个产品都有一个“价格”。但是,每当产品价格发生变化时,该变化就会记录在“ old_prices”表中。

产品表:

id: int
name: string
price: int

old_prices表:

product_id: int
price: int
created_at: int

想象一下,某产品的价格随时间变化了一些。我要完成的是一个列表,其中包含产品的当前价格以及产品的价格历史记录。像这样:

id    name      price     time
1     Shampoo   500       01/01/2000
1     Shampoo   550       06/01/2000
1     Shampoo   700       04/03/2001   <- current price!

3 个答案:

答案 0 :(得分:1)

您需要一个UNION:

select  id, name, price, time 
from products 
union 
select  id, name, price, time 
from old_prices 
order by id, time 

答案 1 :(得分:1)

这对您有用吗?我假设created_at列的日期时间数据类型不是int(如您原始帖子所述)

select id, name, price, time='Current'
from products
union 
select p.id, p.name, op.price, time=convert(varchar(30), created_at, 120)
from products p
inner join old_prices op
on op.product_id = p.id

答案 2 :(得分:0)

使用可以内部联接以通过

关联表和顺序
select  id, name, price,  null  
from products 
union   
select  a.id, a.name, b.price, b.time 
from products a 
inner join  old_prices b on a.id = b.product_id
order by  a.id, a.name, time