2

我有一张股票价格表,需要获取每周第一天的价格。WHERE 子句中的这条 SQL 运行良好,

DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0)

除非周一市场休市。劳动节就是一个很好的例子。我认为使用 COALESCE 会给我周二的价格,如果周一没有的话,但这没有用。

coalesce(DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0), DATEADD(ww, DATEDIFF(ww,0,PriceDt), 1)). 

有人可以帮忙吗?

declare @t table (PriceDt datetime, Symbol nvarchar(10), OpenPric float, ClosePrice float)

insert @t values ('2010-08-02 00:00:0.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-08-09 00:00:00.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-08-16 00:00:00.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-08-23 00:00:00.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-08-30 00:00:00.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-09-07 00:00:00.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-09-13 00:00:00.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-09-20 00:00:00.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-09-27 00:00:00.000', 'SYM', 15.00, 15.10)

select * from @t
where PriceDt = coalesce(DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0), DATEADD(ww, DATEDIFF(ww,0,PriceDt), 1))

(结果中缺少 2010-09-07 00:00:00.000)

2010-08-02 00:00:00.000 SYM 15 15.1
2010-08-09 00:00:00.000 SYM 15 15.1
2010-08-16 00:00:00.000 SYM 15 15.1
2010-08-23 00:00:00.000 SYM 15 15.1
2010-08-30 00:00:00.000 SYM 15 15.1
2010-09-13 00:00:00.000 SYM 15 15.1
2010-09-20 00:00:00.000 SYM 15 15.1
2010-09-27 00:00:00.000 SYM 15 15.1
4

1 回答 1

1

这将为您提供每周表中存在的最早日期(假设您的一周从星期一开始):

select min(Pricedt) Pricedt
from @t
group by DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0)

现在,您可以将该结果加入您的表格,以获取输入数据的一周中第一天的价格:

select t.Pricedt, t.Symbol, t.OpenPric, t.ClosePrice
from
(
    select min(Pricedt) Pricedt
    from @t
    group by DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0)
) d 
join @t t on d.Pricedt = t.PriceDt
于 2014-06-29T15:17:20.643 回答