超市改价

时间:2015-08-24 13:08:37

标签: sql sql-server

我有桌子tr_p

id  date
01  2015-02-03
01  2015-03-12
02  2015-03-12
01  2015-03-13
02  2015-03-21

和表MR_P

id updatedate  price
01 2015-03-01  5000
01 2015-03-13  6000   
02 2015-03-12  4500
02 2015-03-18  5500

现在我想表明:

id    date        price
01    2015-03-02  5000
01    2015-03-12  5000
01    2015-03-13  6000
02    2015-03-12  4500
02    2015-03-21  5500

日期过后的价格变动

1 个答案:

答案 0 :(得分:1)

在我看来,您希望最后为每个ID分配价格。

以下是解决问题的两种方法,请注意这个答案是针对sqlserver 2008 +:

编写的

测试表&数据

DECLARE @tr_p table(id int, date date)
insert @tr_p
values
(01,'2015-03-03'),
(01,'2015-03-12'),
(02,'2015-03-12'),
(01,'2015-03-13'),
(02,'2015-03-21')

DECLARE @MR_P table
(id int, date date, Price int)
insert @MR_P values
(01,'2015-03-01','5000'),
(01,'2015-03-13','6000'),
(02,'2015-03-12','4500'),
(02,'2015-03-18','5500')

外部申请方法:

SELECT 
  t1.id, t1.Date, x.Price
FROM @tr_p t1
OUTER APPLY
( 
  SELECT top 1 Price FROM @MR_P t2 
  WHERE t1.date >= t2.date and t1.id = t2.id 
  ORDER BY  t2.date desc) x
ORDER BY t1.id, x.price

Subselect方法:

SELECT 
  t1.id, 
  t1.Date, 
  (SELECT top 1 Price FROM @MR_P t2 
  WHERE t1.date >= t2.date and t1.id = t2.id 
  ORDER BY  t2.date desc) Price
FROM @tr_p t1
ORDER BY id, price

导致两个查询:

id  Date        Price
1   2015-03-03  5000
1   2015-03-12  5000
1   2015-03-13  6000
2   2015-03-12  4500
2   2015-03-21  5500