0

我有一个简单的表:

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

4 回答 4

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

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

于 2013-03-27T01:11:37.250 回答
0

这是一种根据fromwhichweek表中的最大值动态确定所需周数的方法。您可以通过@end显式分配值(例如尝试使用 22 或 25)而不是使用MAX. 假设您的价格表真的这么简单,这应该可以在 52 周内扩展。

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;
于 2013-03-27T01:39:40.377 回答
-1

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

SELECT
  fromwhichweek, price
FROM
  prices
ORDER BY
  fromwhichweek ASC
于 2013-03-27T00:26:27.197 回答
-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);
于 2013-03-27T01:08:25.597 回答