每周获得价格

时间:2013-03-27 00:23:15

标签: sql sql-server sql-server-2008 sql-server-2008-r2

我有一张简单的表格:

prices(fromwhichweek(int),newprice(int))  
data example:  
1,20  
3,21 
10,30

所以我正在寻找一个sql语句,它返回每周的价格是什么? 像(根据上面的3行):

1,20  
2,20  
3,21  
4,21  
5,21  
6,21  
7,21  
8,21   
9,21  
10,30
... 

4 个答案:

答案 0 :(得分:0)

您需要生成一系列周。以下版本通过在select语句中使用相关子查询来获取价格:

select w.week,
       (select top 1 newprice from prices p where w.week >= p.fromwhichweek
        order by fromwhichweek desc
       ) theprice
from (select 1 as week union all select 2 union all select 3 union all select 4 union all
      select 5 union all select 6 union all select 7 union all select 8 union all
      select 9 union all select 10
     ) w

一些评论。这取决于有一个周列表。这是使用显式子查询完成的。根据数据库的不同,还有其他方法。

答案 1 :(得分:0)

这是一种根据表中最高fromwhichweek值确定动态所需周数的方法。您可以通过明确地将值@end分配给MAX来扩展(例如,尝试使用22或25),而不是使用DECLARE @prices TABLE(fromwhichweek INT, newprice INT); INSERT @prices VALUES (1, 20), (3, 21), (10,30); DECLARE @start INT, @end INT; SELECT @start = MIN(fromwhichweek), @end = MAX(fromwhichweek) FROM @prices; ;WITH x AS ( SELECT TOP (@end-@start+1) n = @start-1+ROW_NUMBER() OVER (ORDER BY [object_id]) FROM sys.all_objects ORDER BY [object_id] ) SELECT fromwhichweek = x.n, newprice = COALESCE(p.newprice, ( SELECT TOP (1) newprice FROM @prices WHERE fromwhichweek <= x.n AND newprice IS NOT NULL ORDER BY fromwhichweek DESC)) FROM x LEFT OUTER JOIN @prices AS p ON x.n = p.fromwhichweek ORDER BY x.n; 。这应该可以在52周的时间内进行扩展,假设您的价格表非常简单。

{{1}}

答案 2 :(得分:-1)

这将为您提供您想要的输出。如果您想要不同的东西,请修改您的问题:)

SELECT
  fromwhichweek, price
FROM
  prices
ORDER BY
  fromwhichweek ASC

答案 3 :(得分:-2)

您可以创建一个填充1-52周的表格。

create table weeks (week int);
insert into weeks values (1), (2), ....(52);

然后,您可以执行以下查询以获取结果。这是一个本机MYSQL查询。如果您使用的是其他sql供应商,则可能需要稍微更改一下。

select A.week, B.price from weeks as A, prices as B where 
    B.fromwhichweek = (select C.fromwhichweek from prices as C where 
                       C.fromwhichweek <= A.week order by C.fromwhichweek desc limit 1);